简体   繁体   English

范围总和与分配的while循环

[英]Range sum with a while loop for an assignment

I am new to Java and I'm trying to do a range sum with a while loop for an assignment.我是 Java 的新手,我正在尝试使用 while 循环对分配进行范围求和。 I need to use a while loop for this and the loop is not storing the total correctly and just adds the two values together.我需要为此使用一个while循环,并且循环没有正确存储总数,只是将两个值相加。

public static void main(String[] args) {
    Scanner keyboard=new Scanner(System.in);
    System.out.println("Enter the first number: ");

    int first = keyboard.nextInt();
    System.out.println("Enter the second number: ");

    int second = keyboard.nextInt();
    if( second < first) {
        System.out.println("The sum is 0");
    }
    else if(second > first) {
        int total = 0;
        while (first < second) {
            total = second + first;
            second = second - 1;
            first = first +1;
            total = second + first;//this does not give the correct total 
        }
    System.out.print("The sum is "+total++);
    }
}

You are updating your total twice in the while loop, and you are changing both first and second variables in the loop.您在 while 循环中更新了两次总数,并且您正在更改循环中的第一个和第二个变量。 It would be clearer to modify just one of the numbers.只修改其中一个数字会更清楚。 I think a for loop is a little easier to read for a sum range.我认为对于总和范围,for 循环更容易阅读。 Here is an example of one that sums inclusive of both ends:这是一个包含两端的示例:

for (int i = first; i <= second; i++) {
  total += i;
}

here is a fix for your while loop (with it being inclusive of both first and second):这是您的 while 循环的修复(包括第一个和第二个):

while (first <= second) {
  total += first;
  first++;
}

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

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