我不明白为什么输出是25
,显然我的错误理解,我认为它是20
,因为:第一个循环将是:i = 2; x = 5
并且那里自i <= m
以来将再增加4个循环,因此5 x 4 = 20
。我知道我错了,但无法弄清楚在哪里。
public class num {
public static void main(String[] args) {
int m, x, i;
x = 0;
i = 1;
m = 5;
while (i<= m){
x = x + m;
i = i + 1;
}
System.out.println(x);
}
}
答案 0 :(得分:4)
让我们试试这个:
x=0;i=1;m=5
while (1<=5) ? yes, so x=0+5; i=2,
while (2<=5) ? yes, so x=5+5; i=3,
while (3<=5) ? yes, so x=10+5; i=4,
while (4<=5) ? yes, so x=15+5; i=5,
while (5<=5) ? yes, so x=20+5; i=6,
while (6<=5) ? no, so exit from loop
因此结果是:x=25
答案 1 :(得分:0)
当遇到这种情况时,请尝试调试和打印。大部分时间你都会找到你的答案:
public class num {
public static void main(String[] args) {
int m, x, i;
x = 0;
i = 1;
m = 5;
System.out.println("Initial : x = " + x + " and i = " + i);
while (i <= m) {
x = x + m;
i = i + 1;
System.out.println("x = " + x + " and i = " + i);
}
System.out.println(x);
}
}
输出:
Initial : x = 0 and i = 1
x = 5 and i = 2
x = 10 and i = 3
x = 15 and i = 4
x = 20 and i = 5
x = 25 and i = 6
25