本文介绍了Java,平均数字列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在下面的Java代码中,我的平均温度降低了1位小数.
In the following Java code, my average temperature is 1 decimal place off.
例如,而不是 69.0
,而是 6.9
.
输入可以是任何10个数字.因此,可以说我输入了10个温度,每个温度为10度.10个输入的总数为100,因此平均值应为10,但我收到的平均值为1.0.
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.
代码:
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");
}
}
推荐答案
您实际上并没有将数字求和.
You're not actually summing the numbers together.
应为 sum + =数字[i];
不是 sum =数字[i];
您似乎也尝试执行两次此操作,这是不必要的.
You also appear to be attempting to do this twice, which is unnecessary.
这篇关于Java,平均数字列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!