嵌套for循环Java混淆

时间:2017-08-17 12:33:38

标签: java

我有一个关于java中嵌套for循环的初学者问题。

vartical-align:top

所以这是我的跟踪表

int sum = 0;
for(int i = 1; i < 3; i++){
    for(int j = i; j>= 0; j--){
        sum += j;
    }
}

我的问题是为什么循环结束时的输出是4?是因为3 + 1?

3 个答案:

答案 0 :(得分:2)

您的跟踪表是错误的。这是正确的:

i j sum
1 1 1
  0 1
2 2 3
  1 4
  0 4

您对j(第二列)的所有值求和,基本上为1 + 0 + 2 + 1 + 0 = 4

答案 1 :(得分:2)

实际上我们需要对您的表格结果进行更正:

i j sum
1 1 1
  0 1
2 2 2 (sum is 2+1(existing sum, sum is not 0 anymore) )
  1 3 (sum is 3 + 1 = 4)
  0 3 (sum is 4+ 0 = 4)

答案 2 :(得分:1)

输出为4,因为Trialtime type Track time Notes Athlete Trialtime type Track time Notes Athlete 20170101 07:15:00 07:15:00 Warmup ABC 85.2 Initial warmup Jon 20170101 07:45:00 07:45:00 Sprint1 ABC 59.44 First Sprint Jon 20170101 08:30:00 08:30:00 TRIAL ABC 57.21 Final attempt Jon 20170101 08:00:00 08:00:00 Warmup ABC 120.51 Initial warmup Bill 20170101 08:40:05 08:40:05 Sprint1 ABC 61.35 First Sprint Bill 20170101 09:15:00 09:15:00 Sprint2 ABC 60.08 Second Sprint Bill 20170101 10:30:00 10:30:00 TRIAL ABC 60.37 Final attempt Bill 20170101 07:15:00 07:15:00 Warmup ABC 85.2 Initial warmup Jon 20170101 07:45:00 07:45:00 Sprint1 ABC 59.44 First Sprint Jon 20170101 08:30:00 08:30:00 TRIAL ABC 57.21 Final attempt Jon 20170101 08:00:00 08:00:00 Warmup ABC 120.51 Initial warmup Bill 20170101 08:40:05 08:40:05 Sprint1 ABC 61.35 First Sprint Bill 20170101 09:15:00 09:15:00 Sprint2 ABC 60.08 Second Sprint Bill 20170101 10:30:00 10:30:00 TRIAL ABC 60.37 Final attempt Bill Trialtime type Track time Notes Athlete 201701023 07:15:00 07:15:00 Warmup ABC 85.2 Initial warmup Jon 201701023 07:45:00 07:45:00 Sprint1 ABC 59.44 First Sprint Jon 201701023 08:30:00 08:30:00 TRIAL ABC 57.21 Final attempt Jon 201701023 08:00:00 08:00:00 Warmup ABC 120.51 Initial warmup Bill 201701023 08:40:05 08:40:05 Sprint1 ABC 61.35 First Sprint Bill 201701023 09:15:00 09:15:00 Sprint2 ABC 60.08 Second Sprint Bill 201701023 10:30:00 10:30:00 TRIAL ABC 60.37 Final attempt Bill 201701023 07:15:00 07:15:00 Warmup ABC 85.2 Initial warmup Jon 201701023 07:45:00 07:45:00 Sprint1 ABC 59.44 First Sprint Jon 201701023 08:30:00 08:30:00 TRIAL ABC 57.21 Final attempt Jon 201701023 08:00:00 08:00:00 Warmup ABC 120.51 Initial warmup Bill 201701023 08:40:05 08:40:05 Sprint1 ABC 61.35 First Sprint Bill 201701023 09:15:00 09:15:00 Sprint2 ABC 60.08 Second Sprint Bill 201701023 10:30:00 10:30:00 TRIAL ABC 60.37 Final attempt Bill 为:

sum

首先添加0 + 1 + 2 + 1 = = 4 ,然后12。您的循环将所有三角形数字加在3以下。三角形数字是从11的数字之和。这些是n136等。