简体   繁体   English

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

[英]Why is my do-while loop not producing the same results as my for & while loops?

I'm trying to write the same loop to calculate the sum of the integers from 1 to the input value, and output the sum 3 different ways, and so far I've completed my for and while loops correctly, and had them output the same result.我正在尝试编写相同的循环来计算从 1 到输入值的整数之和,以及 output 的总和 3 种不同的方式,到目前为止,我已经正确完成了我的 for 和 while 循环,并让它们 output同样的结果。 However, for some reason my do-while loop isn't working properly, and instead of adding the sum of all the numbers together, it just adds one to the user input.但是,由于某种原因,我的 do-while 循环无法正常工作,而不是将所有数字的总和相加,它只是在用户输入中加一。 Can anyone help me figure out how to get it to copy the process of my other loops correctly?谁能帮我弄清楚如何让它正确复制我的其他循环的过程? Attached is my code.附上我的代码。

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);

    }
}

Between the for loop and the do while loop you didn't reset the value of n.在 for 循环和 do while 循环之间,您没有重置 n 的值。 It is still equal to input because of the for loop由于for循环,它仍然等于输入

Before your "do... while()", you have to set n to 0, otherwise n is equal to the number entered plus one.在“do...while()”之前,您必须将 n 设置为 0,否则 n 等于输入的数字加一。 If you do so, you will have the same answer.如果你这样做,你将得到相同的答案。

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

Tip: avoid when possible to use a variable is several places and have long living variables (especially when they are mutable).提示:尽可能避免在多个地方使用变量并且具有长期存在的变量(尤其是当它们是可变的时)。

The for (n=0; n<input; n++) could be replace with for (int i=0; i<input; i++) for example, which avoid using an existing variable and avoid complex state.例如, for (n=0; n<input; n++)可以替换for (int i=0; i<input; i++) ,这样可以避免使用现有变量并避免复杂的 state。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM