为什么经过两次循环递增后变量值达到5050? (循环到 100)

Why does variable value reach 5050 after increment through two loops? (loop till 100)

我正在阅读一本关于 C 编程的初学者书籍,其中有一些练习。 这是其中之一,问题是以下循环的结果是什么...

int main()
{
    int result = 0;

    for (int i = 1; i <= 100; i++)
    {
        for (int j = 1; j <= i; j++)
        {        
            result++;
        }
    }      

    printf("%d", result);

    return 0;
}

我的 'rational' 答案应该是 1000,但为什么正确答案是 5050

第一次,内循环会运行一次,因为i1,将1添加到result。第二次,它会 运行 两次,因为 i2,将 2 添加到 result 第三次,内部循环将 运行三次,因为 i3,将 3 添加到 result。以此类推,直到 100.

最终,这会将 1 + 2 + 3 + 4 + … + 97 + 98 + 99 + 100 添加到 result。这个值为5050:第100个三角形数

如果你的编译器很聪明(例如gcc -O2),它会发现最内层的循环只是一个增量,然后编译:

for (int i = 1; i <= 100; i++)
{
    for (int j = 1; j <= i; j++)
    {        
        result++;
    }
}

至:

for (int i = 1; i <= 100; i++)
{
    result += j;
}

如果你的编译器真的聪明(例如clang -O2),它会把它编译成一个简单的result = 5050;,但这样的优化最终可能是确实编译速度很慢(它必须事先运行代码来计算值的含义,除非它是特殊情况的特定示例,这会使编译器占用更多space).

@wizzwiss34 的回答是正确的...添加更多上下文。在数学中,这被称为 finite series,您正在做的是使用 C 实现此数学函数。

A finite series is a summation of a finite number of terms. An infinite series has an infinite number of terms and an upper limit of infinity. This tutorial will deal with finite series. Infinite series will be covered in the calculus tutorials.

在这种情况下,序列是 100+99+98+97...+1 = 5050

对于您每次添加 i-1 的总数 i