[英]i have initialized a variable with zero at the top of the function so during a loop the value changes?
public class maxsubarraysum {
public static void main(String[] args) {
int numbers[] = { 1, -2, 6, -1, 3 };
printmsasum(numbers);
}
public static void printmsasum(int numbers[]) {
int currsum=0;//declared and initialized
int maxsum = Integer.MIN_VALUE;
for (int i = 0; i < numbers.length; i++) {
int start = i;
for (int j = i; j < numbers.length; j++) {
int end = j;
currsum = 0; //here is what i dont understand why i have to again give it zero to run it properly what its is called ? means am i missing any concept? pls help in loops does value changes?
for (int k = start; k <= end; k++) {
currsum += numbers[k];
}
System.out.println(currsum);
if (maxsum < currsum) {
maxsum = currsum;
}
}
}
System.out.println("the maximum sub array sum is = " + maxsum);
}
}
i tried it with only declaring and initializing the currsum variable with zero,then the output is wrong then inside the second nested loop why i have to initialized it with zero for correct answer?我尝试过只用零声明和初始化 currsum 变量,然后 output 是错误的然后在第二个嵌套循环中为什么我必须用零初始化它以获得正确答案?
You are declaring cursum in the function so its scope is the entire function, which contain all the loops.您在 function 中声明 cursum,因此它的 scope 是整个 function,其中包含所有循环。 It will not be reset to 0 on entering your inner loop as its scope is outside of that loop.
它不会在进入您的内部循环时重置为 0,因为它的 scope 在该循环之外。
You could just move its declaration inside the second loop, right before your "k" loop.您可以将其声明移到第二个循环内,就在“k”循环之前。 That will restrict its scope to the iteration over k which looks to be the partial sum you want.
这会将其 scope 限制为对 k 的迭代,这看起来是您想要的部分和。
That would be replacing your那将取代你的
cursum = 0;
with和
int cursum = 0;
You are changing currsum
in every iteration currsum += numbers[k];
您在每次迭代中都在更改
currsum
currsum += numbers[k];
, so to check every new result, you have to reset the currsum
. ,因此要检查每个新结果,您必须重置
currsum
。 You don't have to declare it before loops, you can actually declare it in the same place you are setting it to 0.您不必在循环之前声明它,您实际上可以在将其设置为 0 的同一位置声明它。
Tip: You also don't have to initalize start
and end
variables, you can use i
and j
提示:您也不必初始化
start
和end
变量,您可以使用i
和j
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.