为什么 x 是 5050?

huangapple go评论67阅读模式
英文:

Why the x is 5050?

问题

for(i = 1; i <= 100; i++)
    for(j = i; j <= 100; j++)
        x++;
System.out.println(x);

一开始我以为结果会是 10,000,但实际上是 5050。为什么?i 发生了什么变化?

英文:
for(i = 1;i &lt;= 100;i++)
    for(j = i; j &lt;= 100; j++)
        x++;
System.out.println(x);

First I thought that the result would be 10.000, but it was 5050. Why? What does the i changes?

答案1

得分: 8

5050这个答案是正确的,假设x为0(根据你的结果推断出来的)。之所以不是10000,是因为代码中的这行:j = i,而不是例如j = 1,这使得结果为100 + 99 + 98 + ... + 1 = 5050。

英文:

The answer 5050 is correct, given the assumption that x is 0 (as it appears based on your results). The reason it is not 10,000 is the line j = i instead of e.g. j = 1, which makes it 100 + 99 + 98 + ... + 1 = 5050.

答案2

得分: 2

起初,i1,因此 j 也从 1 变化到 100,内部循环执行了 100 次迭代,这意味着 x 被增加了 100 次。

接下来,i 变为 2,所以 j 从 2 变化到 100。这意味着进行了 99 次迭代,x 被增加了 99 次,依此类推...

这是从 1 累加到 100 所有数字的和,即 (100 * (100 + 1)) / 2 == 5050

英文:

At first i is 1, so j goes from 1 too 100 and the inner loop does 100 iterations, which means x is incremented 100 times.

The next time, i becomes 2, so j goes from 2 to 100. That means 99 iterations and x is incremented 99 times and so on and so forth...

That's the sum of all numbers from 100 to 1, which is (100 * (100 + 1)) / 2 == 5050

答案3

得分: 0

内部循环在外部循环的每次迭代中执行(100 - i)次。即当外部循环中的i的值为0时,内部循环执行100次;当外部循环中的i的值为1时,内部循环执行99次,依此类推。将所有这些值相加得到100 + 99 + 98 + ... + 1 = 5050

英文:

The inner loop executes (100 - i) times on each iteration of the outer loop. i.e. when the value of i = 0 in the outer loop, the inner loop executes 100 times, when the value of i = 1 in the outer loop, the inner loop executes 99 times and so on and so forth. When adding all these values 100 + 99 + 98 + ... + 1 = 5050

huangapple
  • 本文由 发表于 2020年10月7日 06:54:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64234855.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定