为何我的do-while循环与for、while循环结果不一致?
问题排查与修正:do-while循环求和逻辑错误
问题根源
执行do-while循环前,变量n已经被前面的for循环修改为input + 1。do-while的特性是先执行一次循环体,再判断条件,所以会先把input+1加到total3中,随后n自增为input+2,此时判断n<=input条件不成立,循环直接终止,最终只累加了一个错误数值。
修正方案
在do-while循环开始前,将n重置为0,确保循环起始值和另外两种循环保持一致,从0开始累加。
修正后的完整代码
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:"); // 重置n为0,保证循环起始值正确 n = 0; do { total3 += n; n++; System.out.println(total3); } while(n<=input); } }
补充说明
如果需求是从1开始求和(而非0),只需将三个循环的起始n改为1,循环条件保持n<=input即可,三种循环的逻辑会完全一致。
内容的提问来源于stack exchange,提问作者Cameron Cross
相关产品推荐
相关产品推荐

