Iam Learning Java,我无法弄清楚为什么在上面的代码中答案是20:
int arrays[]={1,2,3,4,5};
int x = 4;
int y = 0;
for(int i=0; i < 5; i++){
y+=arrays[x-i]*i;
}
System.out.println(y);
请给我解释一下 谢谢:)
答案 0 :(得分:3)
我为您调试它!
y = y + [4-0]〜5 * 0 => 0
0 = 0 + [4-1]〜4 * 1 => 4
4 = 4 + [4-2]〜3 * 2 => 10
10 = 10 + [4-3]〜2 * 3 => 16
16 = 16 + [4-4]〜1 * 4 => 20
答案 1 :(得分:2)
如果您在for循环的开头编写了此代码段
System.out.println("y=" + y + "+" + arrays[x-i] + "*" + i + " => " + (y + arrays[x-i] * i));
...您得到以下输出:
y=0+5*0 => 0
y=0+4*1 => 4
y=4+3*2 => 10
y=10+2*3 => 16
y=16+1*4 => 20