使用while循环如何计算两个值之间的总和,包括这些值?

时间:2012-12-03 05:05:17

标签: while-loop java.util.scanner

import java.util.Scanner;
public class Q6 {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Please type two numbers ");
        int a = keyboard.nextInt();
        int b = keyboard.nextInt();
        int sum = 0; 
        if (a <= b) {
            while (a <= b) {
                sum += a;
                a--;
            }
        }
        else if (b <= a) {
            while (b <= a) {
                sum += a;
                a++;
            }
        }
        System.out.print("The sum of the numbers between " + a + " and " + b + " is " + sum);
    }
}   

我遇到的主要问题是它为每个输入提供了总和-1073741823。应该发生的是当我输入两个值,先说1然后4,它应该将1 + 2 + 3 + 4加在一起,如果第一个输入大于第二个输入,如4,那么1将是4 + 3 + 2 + 1.我不明白为什么不这样做。

3 个答案:

答案 0 :(得分:0)

您想要对[a,b]范围内的数字求和,请尝试以下方法。

import java.util.Scanner;
public class Q6 {
  public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.print("Please type two numbers ");
    int a = keyboard.nextInt();
    int b = keyboard.nextInt();
    int sum = 0; 

    int s = Math.min(a, b);
    int e = Math.max(a, b);

    while (s <= e) {
      sum += s;
      s++;
    }

    System.out.print("The sum of the numbers between " + a + " and " + b + " is " + sum);
  }
}   

答案 1 :(得分:0)

你不应该在第一个while loop递减

而不是a--;a++;

而不是while (b <= a) {while (b >= a) {

一起

import java.util.Scanner;
public class Q6 {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Please type two numbers ");
        int a = keyboard.nextInt();
        int b = keyboard.nextInt();
        int sum = 0; 
        if (a <= b) {
            while (a <= b) {
                sum += a;
                a++;
            }
        }
        else if (b <= a) {
            while (b >= a) {
                sum += b;
                b--;
            }
        }
        System.out.print("The sum of the numbers between " + a + " and " + b + " is " + sum);
    }
}   

答案 2 :(得分:0)

您需要切换a--a++。你只需要切换你的案件。

现在的方式,如果a为1而b为4,则会进入第一个if / while设置,它会将第一个a添加到sum,但随后递减a,将其移离b,而不是更近。因此,您的循环将继续,直到a溢出。可能不是你想要的。

如果b小于a,则会发生类似的事情。

另外,正如@ rafael-rendon-pablo的例子所示,还有很多其他方法可以重写代码。