当我运行该程序时,它会查找最大值,但总是打印0.0作为最小值。查找数组的最小值和最大值
当我使用Double.POSITIVE_INFINITY和Double.NEGATIVE_INFINITY而不是将最小值和最大值设置为x [0]时,它可以正常工作。
使用Math.min和Math.max也给我同样的错误,但也适用于Double.POSITIVE_INFINITY和Double.NEGATIVE_INFINITY。我看了其他几个类似的问题,我不允许使用Array.sort或任何其他人发布的建议。我只是想知道为什么设置两个变量到x [0]只能用于查找最大数字,无论我是首先声明该变量,第二次还是将其设置为相等(Double largest,smallest = x [0]) 。
public class MaxAndMin {
public static void main (String[] args) {
Scanner s= new Scanner(System.in);
System.out.println("How many numbers would you like to enter?");
int n= s.nextInt();
double[] x= new double[n];
double smallest= x[0]; //double smallest= Double.POSITIVE_INFINITY;
double largest= x[0]; //double largest= Double.NEGATIVE_INFINITY;
for (int i=0; i<x.length; i++) {
x[i]= kbd.nextDouble();
if (x[i] > largest) {
largest = x[i];
} else if (x[i] < smallest) {
smallest = x[i];
}
}
System.out.println("Smallest number: " + smallest + " Largest number: " + largest);
}
}
'x [0] == 0',因为新的双数组元素被初始化为零。 –