为什么我的 do-while 循环没有产生与我的 for & while 循环相同的结果?



我正在尝试编写相同的循环来计算从1到输入值的整数之和,并以3种不同的方式输出总和,到目前为止,我已经正确地完成了for和while循环,并让它们输出相同的结果。然而,由于某种原因,我的do while循环无法正常工作,它没有将所有数字的总和相加,而是将一个数字添加到用户输入中。有人能帮我弄清楚如何让它正确地复制我其他循环的过程吗?附件是我的代码。

import java.util.Scanner;
public class CountLoop{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int total = 0;
int total2 = 0;
int total3 = 0;
int n = 0;

System.out.println("Please input a positive integer");
int input = sc.nextInt();
System.out.println("while loop:");
while(n<=input){
total += n;
n++;
System.out.println(total);
} 

System.out.println(" ");

System.out.println("for loop:");
for(n = 0; n <= input; n++){
total2 += n;
System.out.println(total2);
}
System.out.println(" ");

System.out.println("do while loop:");
do {
total3 += n;
n++;
System.out.println(total3);
} while(n<=input);
}
}

在您的"do…while((";,必须将n设置为0,否则n等于输入的数字加1。如果你这样做,你会得到同样的答案。

System.out.println("do while loop:");
n = 0;
do {
total3 += n;
n++;
System.out.println(total3);
} while(n<=input);

提示:避免在可能的情况下使用一个变量是几个地方的,并且有长期存在的变量(尤其是当它们是可变的(。

例如,for (n=0; n<input; n++)可以替换为for (int i=0; i<input; i++),从而避免使用现有变量并避免复杂状态。

最新更新