gpt4 book ai didi

java - 为什么变量初始化是多余的?

转载 作者:行者123 更新时间:2023-11-29 04:51:04 25 4
gpt4 key购买 nike

我已经在 UVa Online Judge 上解决了一个 3*N + 1 问题 (100),但有一件事我不明白,但我猜它与 Java 有关,而不是算法本身。所以这是代码:

private static int maxCycleLength(int lo, int hi) {
maxLength = 0;
int n = 0;
int length = 0;

for (int i = lo; i <= hi; i++) {
// It's the first time we're computing the cycle length for n
if (lengths[i] == 0) {
n = i;
length = 1;
while (n != 1) {
if ((n % 2) == 0) {
n = n >> 1;
length++;
}
else {
n = 3 * n + 1;
n = n >> 1;
length += 2;
}
}
lengths[i] = length;
}
// Otherwise we just look it up
else
length = lengths[i];

// Check if the current cycle length is the maximum
if (length > maxLength)
maxLength = length;
}
return maxLength;

我不明白的地方:我的 IDE (IDEA) 告诉我,在这段代码中,变量 nlength 的初始化> 是多余的,但是,必须初始化 maxLength,如果我不这样做,它就不会编译。

为什么会这样? maxLengthnlength 有何不同?

最佳答案

在所有代码路径上,您在尝试从中读取值之前初始化nlength。无论发生什么,您最初分配给它们的值都不会被使用,因为您会在需要之前用其他东西覆盖它。

maxLength 虽然会在您为其分配新值之前读取,当您进行 length > maxLength 比较时,或者在 return,如果 for 循环被跳过。由于它在第一次传递时不会有值,因此您需要给它一个起始值才能使用。

关于java - 为什么变量初始化是多余的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35383779/

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