Sum和Average给出错误的输出

时间:2017-11-15 09:05:26

标签: java

我有这个代码用于计算总和和平均值,但它给了我错误的计算。你知道为什么吗?

import java.util.Scanner;

public class SumAndAverage {
   public static void main(String args[]) {
       Scanner input = new Scanner(System.in);

       System.out.print("Enter a lower bound then an upper bound:");

       double sum = 0;
       double average;
       int lowerbound = input.nextInt();
       int upperbound = input.nextInt();

       System.out.println("The upper bound " + upperbound);

       for(int number = lowerbound; number <= upperbound; number++) {
           sum += number;
       }

       average = sum/upperbound;
       System.out.println("The sum is " +sum);
       System.out.println("The average is " + average);
   }
}

2 个答案:

答案 0 :(得分:3)

要获得正确的平均值,您必须将总和除以元素数。

因此平均值不是:

average = sum/upperbound;

它&#39; S:

average = sum/(upperbound-lowerbound+1);

答案 1 :(得分:0)

要获得总和,您应该添加两个数字。不需要循环。即使下限大于上限,这也会使您的代码正常工作。

要获得两个数字的平均值,你应该将它们除以它们的数量而不是它们的上限。

示例:

package foo;

import java.util.Scanner;

public class SumAndAverage {

    public static void main(String args[]) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter a lower bound then an upper bound:");

        double sum = 0;
        double average;
        int lowerbound = input.nextInt();
        int upperbound = input.nextInt();

        System.out.println("The upper bound " + upperbound);

        sum = lowerbound + upperbound;
        // for (int number = lowerbound; number <= upperbound; number++) {
    //
    // sum += number;
    //
    // }

    average = sum / 2;
    System.out.println("The sum is " + sum);
    System.out.println("The average is " + average);

 }
}