【发布时间】:2019-09-21 14:25:42
【问题描述】:
我需要添加代码来查找输入数字的最小值、最大值和平均值。 最好使用 arraylist 吗?
感谢您的建议。很高兴听到我将来会了解数组列表(因为我现在对它们完全不熟悉),并坚持给出的建议。再次感谢。
【问题讨论】:
-
“最佳”在什么意义上?你试过什么?您遇到的具体问题是什么?
标签: java arraylist max average min
我需要添加代码来查找输入数字的最小值、最大值和平均值。 最好使用 arraylist 吗?
感谢您的建议。很高兴听到我将来会了解数组列表(因为我现在对它们完全不熟悉),并坚持给出的建议。再次感谢。
【问题讨论】:
标签: java arraylist max average min
如果您不需要手动计算(即这不是家庭作业),那么您可以使用内置的统计功能:
DoubleStream.generate(input::nextDouble).takeWhile(v -> v != 999).summaryStatistics();
这将为您提供最小值、最大值、计数、平均值和总和,而无需您进行任何手动计算。
【讨论】:
你也可以不用 ArrayList 来实现。 需要使用 MIN、MAX、SUM 和 COUNTER 变量并使用第一个用户输入初始化 MIN 和 MAX。
当用户输入任何值时,检查 MIN、MAX 并将其添加到 SUM。
您可以登录来计算循环的平均外侧(SUM/COUNTER)
【讨论】:
如果您需要手动计算(为了了解其工作原理),您只需(以伪代码形式):
// NOTE: this is pseudo-code only, not executable code!
// start with the min set to the largest float
float min = Float.MAX_VALUE;
// start with the max set to the smallest float
float max = Float.MIN_VALUE;
// start with an average of 0 and count of 0
float average = 0.0;
int count = 0;
// for each value input
{
// get the value from the user
float nextValue = getValueFromUser(...);
// update the min value
if (nextValue < min) {
min = nextValue;
}
// update the max value
if (nextValue > max) {
max = nextValue;
}
// recalculate the average
float sum = average * count;
count++;
sum += nextValue;
average = sum / count;
} // loop until the user is done
// print the min, max and average
【讨论】: