此代码连续两天打印出阵列的最大温度波动。
但我真的不明白,if语句会发生什么。
有人请你这么好解释一下吗?
public class NurTests {
public static void main(String[] args) {
int[] temperature = { 12, 14, 9, 12, 15, 16, 15, 15, 11, 8, 13, 13, 15, 12 };
int maxTempDiff = 0;
int foundDay = 0;
for (int i = 0; i < temperature.length; i++) {
int newMaxDiff = 0;
if ((i + 1) < temperature.length) {
if (temperature[i] < temperature[i + 1]) {
newMaxDiff = temperature[i + 1] - temperature[i];
}
if (temperature[i] >= temperature[i + 1]) {
newMaxDiff = temperature[i] - temperature[i + 1];
}
if (maxTempDiff < newMaxDiff) {
maxTempDiff = newMaxDiff;
foundDay = i;
}
}
}
}
}
提前致谢。
答案 0 :(得分:3)
我添加了一些评论 - 应该有所帮助。
// Make sure we don't access beyond the length of the array.
if ((i + 1) < temperature.length) {
// Is this temp less than the next one?
if (temperature[i] < temperature[i + 1]) {
// New max diff is next minus this.
newMaxDiff = temperature[i + 1] - temperature[i];
}
// Is this temp greater than or equal to the next one?
if (temperature[i] >= temperature[i + 1]) {
// New max diff is this minus next.
newMaxDiff = temperature[i] - temperature[i + 1];
}
// Is the new temp diff the greatest so far?
if (maxTempDiff < newMaxDiff) {
maxTempDiff = newMaxDiff;
foundDay = i;
}
}
答案 1 :(得分:2)
if ((i + 1) < temperature.length)
可以通过循环运行直到i < temperature.length-1
来消除:这种方式i+1
将一直是数组的有效索引,因此不需要检查if
- s处理温度上升和下降,并且对于这两种变化,它们在最后提供正数。 Java中有absolute value,Math.abs
的数学函数。结合在一起:
for (int i = 0; i < temperature.length - 1; i++) {
int newMaxDiff = Math.abs(temperature[i] - temperature[i + 1]);
if (maxTempDiff < newMaxDiff) {
maxTempDiff = newMaxDiff;
foundDay = i;
}
}