【发布时间】:2017-12-29 21:31:45
【问题描述】:
这段代码打印出数组连续两天的最大温度波动。
但我不太明白 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;
}
}
}
}
}
提前致谢。
【问题讨论】:
-
哪个 if 语句?所有这些?
-
理解这样的代码的最好方法是用你的调试器单步调试它,并检查每一行之后的所有变量。
-
第二个和第三个:)
-
第一个和第二个 if 相当混乱。我会使用绝对差异:
newMaxDiff = Math.abs(temperature[i + 1] - temperature[i]);
标签: java arrays if-statement