简体   繁体   English

为什么 x 是 5050?

[英]Why the x is 5050?

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

First I thought that the result would be 10.000, but it was 5050. Why?一开始我以为结果是 10.000,但结果是 5050。为什么? What does the i changes? i 有什么变化?

The answer 5050 is correct, given the assumption that x is 0 (as it appears based on your results).答案 5050 是正确的,假设x为 0(根据您的结果显示)。 The reason it is not 10,000 is the line j = i instead of eg j = 1 , which makes it 100 + 99 + 98 + ... + 1 = 5050.它不是 10,000 的原因是行j = i而不是例如j = 1 ,这使它成为 100 + 99 + 98 + ... + 1 = 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.起初i1 ,所以j从 1 到 100 并且内部循环进行 100 次迭代,这意味着x增加了 100 次。

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...下一次, i变为2 ,因此j从 2 变为 100。这意味着 99 次迭代, x增加 99 次,依此类推……

That's the sum of all numbers from 100 to 1, which is (100 * (100 + 1)) / 2 == 5050这是从 100 到 1 的所有数字的总和,即(100 * (100 + 1)) / 2 == 5050

The inner loop executes (100 - i) times on each iteration of the outer loop.内循环在外循环的每次迭代中执行(100 - i) times ie 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.即外循环中i = 0时,内循环执行100 times ,外循环中i = 1时,内循环执行99 times ,以此类推。 When adding all these values 100 + 99 + 98 + ... + 1 = 5050将所有这些值相加时100 + 99 + 98 + ... + 1 = 5050

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM