Java, averaging a list of numbers

2019-08-20 12:14发布

问题:

In the following Java code, my average temperature is 1 decimal place off.

For example Instead of being 69.0 it's 6.9.

The input can be any 10 numbers. So lets say I input 10 temperatures and each 1 is 10 degrees. The total for the 10 inputs is 100, so the average should be 10 but instead I'm receiving an average of 1.0.

Code:

import java.util.Scanner;
public class NumberAboveAverage {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        final int TotalTemps = 10;
        double[] numbers = new double[TotalTemps];
        double sum = 0;
        double average = 0;
        double max = 0;
        for (int n = 0; n < numbers.length; n++) {
            System.out.print("Enter a temperature: ");
            numbers[n] = input.nextInt();

            if (numbers[n] > max) {
               max = numbers[n];
            }
            sum = numbers[n];
        }

        for (int i = 0; i < numbers.length; i++) {
            sum = numbers[i];
        }

        average = sum / 10;    //average is not an average of the numbers.
        System.out.println("Average temp = " + average);

        int count = 0;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] > average) {
               count++;
            }
        }
        System.out.println(count + " days were above average");
    }
}

回答1:

You're not actually summing the numbers together.

It should be sum += numbers[i];

not sum = numbers[i];

You also appear to be attempting to do this twice, which is unnecessary.



回答2:

You are missing a +

sum = numbers[n];

needs to be

sum += numbers[n];

This does nothing,

 for (int i = 0; i < numbers.length; i++) {
    sum = numbers[i];
 }


回答3:

You sum twice (second for-loop) and do it wrongly with:
sum = numbers[n];
instead of:
sum += numbers[n];

You should change your code to:

...
         for (int n = 0; n < numbers.length; n++) {
            System.out.print("Enter a temperature: ");
            numbers[n] = input.nextInt();

            if (numbers[n] > max) {
               max = numbers[n];
            }
            sum += numbers[n];
         }

         // SECOND FOR LOOP REMOVED !!!

         average = sum / 10;
         System.out.println("Average temp = " + average);

        ...


回答4:

Replace

average = sum / 10;

with

average = sum / 10.0;


标签: java average