gpt4 book ai didi

java - 在用户输入的数字列表中查找最小和最大的数字

转载 作者:行者123 更新时间:2023-12-01 17:51:03 25 4
gpt4 key购买 nike

我需要帮助显示用户输入的平均值、最小和最大数字,但我只能显示平均值和最大数字。这里还有另一个类似的问题,但没有完全解决,只给出了最小的数字。如果除了 Math.min 和 Math.max 之外还有其他方法,我们将不胜感激。

import java.text.DecimalFormat;
import java.util.Scanner;

public class ProblemSet3_1 {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat dec = new DecimalFormat();

int snum = 0;
int height = 0;
int add = 0;
double avg = 0;
int largest = 0;
int smallest = 0;


System.out.print("How much students are in your class?" + '\n');
snum = input.nextInt();


for (int i = 1; i <= snum; i++) {
System.out.print("How tall is student #" + i + "?" + '\n');
height = input.nextInt();

add += height;
avg = add / i;

if (height > largest) {
largest = height;
}

}
System.out.print("The average height is " + avg + ", while the tallest is " + largest + " , and the shortest is " + smallest + ".");

}
}

最佳答案

是的,有一个非常简单的使用流的方法:

IntSummaryStatistics stats = IntStream.generate(input::nextInt).limit(snum)
.summaryStatistics();

stats 对象现在保存平均值、计数、最大值、最小值、总和。

编辑:抱歉,刚刚意识到您也想要一条提示消息:

IntStream.rangeClosed(1, snum).map(i -> {
System.out.println("How tall is student " + i + "?");
return input.nextInt();}).summaryStatistics();

关于java - 在用户输入的数字列表中查找最小和最大的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50053282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com