gpt4 book ai didi

java - 解释代码(带有数组的 if 语句)

转载 作者:行者123 更新时间:2023-11-30 06:05:54 24 4
gpt4 key购买 nike

此代码打印出阵列连续两天的最大温度波动。

但我不太明白 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com