gpt4 book ai didi

java - 数组问题中的最小最大

转载 作者:行者123 更新时间:2023-11-30 07:31:13 25 4
gpt4 key购买 nike

所以我编写了一个程序来查找五个数字集的最大值和最小值。它在大多数情况下都有效,但是当我输入一组数字(例如 {5,6,7,8,9})时,它会输出 9 作为最大值,但输出 0 作为最小值。任何想法或建议。 导入java.util.Scanner;

public class MinMax {
public static void main (String [] args) {
@SuppressWarnings("resource")
Scanner in = new Scanner (System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
int i = 0;
double max = 0.0;
double min = 0.0;

System.out.println("Enter five numbers.");
System.out.println();

while (i < NUM_ELEMENTS) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
i++;
System.out.println();
}

for (i = 0; i < userVals.length; i++) {
if (userVals[i] > max) {
max = userVals[i];
}
else if (userVals[i] < min) {
min = userVals[i];
}
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);
}

}

最佳答案

min 默认为超出范围的数字(例如 Double.MAX_VALUE),将 max 默认为 Double.MIN_VALUE。您还可以通过删除第二个循环来简化代码;您可以在一个循环中执行逻辑,并且可以使用 Math.max(double, double) 和 Math.min(double, double)。比如,

Scanner in = new Scanner(System.in);
final int NUM_ELEMENTS = 5;
double[] userVals = new double[NUM_ELEMENTS];
System.out.println("Enter five numbers.");
System.out.println();
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
for (int i = 0; i < NUM_ELEMENTS; i++) {
System.out.println("Enter next number: ");
userVals[i] = in.nextDouble();
min = Math.min(min, userVals[i]);
max = Math.max(max, userVals[i]);
}
System.out.println("Max number: " + max);
System.out.println("Min number: " + min);

关于java - 数组问题中的最小最大,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36108830/

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