aprogamer
aprogamer

Reputation: 21

Sum and Average gives incorrect output

I have this code for calculating sum and average, but it gives me wrong calculations. Do you have any idea why?

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

Upvotes: 2

Views: 352

Answers (2)

sho
sho

Reputation: 44

To get the sum you should just add the two numbers. No for loop is needed. This makes your code work even if the lowerbound is larger than the upperbound.

To get the average of two numbers you should divide them by their count not their upper bound.

Example:

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

 }
}

Upvotes: 0

Eran
Eran

Reputation: 393836

To get the correct average you must divide the total sum by the number of elements.

Therefore the average is not:

average = sum/upperbound;

It's:

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

Upvotes: 3

Related Questions