此代码打印出阵列连续两天的最大温度波动。
但我不太明白 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;
}
}
}
}
}
提前致谢。
最佳答案
我添加了一些评论 - 应该有帮助。
// 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;
}
}
关于java - 解释代码(带有数组的 if 语句),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45278176/