0

在下面的 Java 代码中,我的平均温度是小数点后 1 位。

例如,而不是69.0它的6.9.

输入可以是任意 10 个数字。所以假设我输入了 10 个温度,每个 1 是 10 度。10 个输入的总数为 100,因此平均值应为 10,但我收到的平均值为 1.0。

代码:

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

4 回答 4

10

您实际上并没有将数字相加。

它应该是sum += numbers[i];

不是sum = numbers[i];

您似乎还试图这样做两次,这是不必要的。

于 2012-07-11T20:41:13.197 回答
1

您求和两次(第二个 for 循环)并错误地使用:
sum = numbers[n];
而不是:
sum += numbers[n];

您应该将代码更改为:

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

        ...
于 2012-07-11T20:42:31.580 回答
1

你错过了一个+

sum = numbers[n];

需要是

sum += numbers[n];

这无济于事,

 for (int i = 0; i < numbers.length; i++) {
    sum = numbers[i];
 }
于 2012-07-11T20:43:23.163 回答
-1

代替

average = sum / 10;

average = sum / 10.0;
于 2012-07-11T20:41:07.970 回答