在下面的 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");
}
}