我的代码打印出我想要的输出:The sum is 45
。
int sum = 0, i = 1;
while (i < 10) {
sum = sum + i;
i++;
} System.out.println("The sum is " + sum);
如果我在下面编写此代码,为什么我的程序不能正常工作?
int sum = 0;
while (sum < 10) {
sum = sum + 1;
} System.out.println("The sum is " + sum);
输出变为The sum is 10
而不是The sum is 45
。
答案 0 :(得分:1)
正如其他人在评论中所述,您需要将while(sum<10)
替换为while(sum<45)
。要理解它,你可以在循环中打印出sum
的值(实际调试你的代码可能会更好,但也许现在这个步骤太过分了。)
int sum = 0;
while (sum<45){ // <-- this is where you went wrong
System.out.println("sum: " + sum);
sum = sum + 1;
}
System.out.println("Finished! The final sum is "+ sum);
答案 1 :(得分:1)
因为
while (sum < 10)
检查总和为9,所以你必须调整它,所以当它达到9时它将是9 + 1 = 10.所以你必须使用:
while (sum < 45)
这样当它达到44时,将添加1并且答案将是45。 因此代码摘录将如下:
int sum = 0;
while (sum < 45) { //it is 45 here instead of 10 as you had done it.
sum = sum + 1;
} System.out.println("The sum is " + sum);