int min = temperature[0];
//Here, i have initialized the minium array.
else if(temperature[i] < min) {
min = temperature[i];
这里我比较了数组中的值。但由于min的初始化为0.它始终为最小值零。我如何解决它。这是我的整个代码。
int[] temperature = new int[12];
Scanner kb = new Scanner(System.in);
int min = temperature[0];
int max = temperature[0];
int counter = 0;
for (int i = 0; i < temperature.length; i++) {
System.out.println("Please enter the temperature:" + i);
temperature[i] = kb.nextInt();
counter += temperature[i];
if (temperature[i] > max) {
max = temperature[i];
}
else if(temperature[i] < min) {
min = temperature[i];
}
}
int average = counter / temperature.length;
System.out.println("Displaying the average temperature:" + average);
System.out.println("The lowest temperature is:" + min);
System.out.println("The highest temperaature is:" + max);
}
}
答案 0 :(得分:3)
逻辑上删除else
- 如果该值小于我们想要更新当前最小值的当前最小值(无论当前最大值的状态如何)。实际上,我们可以使用Math.max(int, int)
和Math.min(int, int)
使其更清晰。并且,我们无法在不读取输入的情况下将min
和max
默认为初始值(除非我们使用明确荒谬的值)。像,
int[] temperature = new int[12];
Scanner kb = new Scanner(System.in);
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE, counter = 0;
for (int i = 0; i < temperature.length; i++) {
System.out.println("Please enter the temperature:" + i);
temperature[i] = kb.nextInt();
counter += temperature[i];
max = Math.max(max, temperature[i]);
min = Math.min(min, temperature[i]);
}
int average = (int) (counter / (double) temperature.length);
System.out.println("Displaying the average temperature:" + average);
System.out.println("The lowest temperature is:" + min);
System.out.println("The highest temperaature is:" + max);
否则,您需要两个 循环。最后,请注意您在计算average
时使用整数数学。你可能想要浮点数学。
或,甚至更好,请使用{/ 3}}
int[] temperature = new int[12];
Scanner kb = new Scanner(System.in);
for (int i = 0; i < temperature.length; i++) {
System.out.println("Please enter the temperature:" + i);
temperature[i] = kb.nextInt();
}
IntSummaryStatistics iss = IntStream.of(temperature).summaryStatistics();
System.out.println("Displaying the average temperature:" + iss.getAverage());
System.out.println("The lowest temperature is:" + iss.getMin());
System.out.println("The highest temperaature is:" + iss.getMax());
System.out.println("The total of all values is:" + iss.getSum());
答案 1 :(得分:1)
解决方案是将min初始化为数组的第一个值,如果数组至少有一个值。如果你真的想要,也可以将它设置为Integer.MAX_VALUE。