我已经初始化了一个变量与零在函数的顶部,所以在循环期间值的变化?


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);
}
}

我尝试了它只声明和初始化零的current变量,然后输出是错误的,然后在第二个嵌套循环为什么我要用零初始化它的正确答案?

您在函数中声明cursum,因此它的作用域是整个函数,其中包含所有循环。它不会在进入内部循环时重置为0,因为它的作用域在循环之外。

你可以把它的声明移到第二个循环中,就在你的"k"循环。这将把它的范围限制在k上的迭代,这看起来就是你想要的部分和。

这将取代你的

cursum = 0; 

int cursum = 0;

您在每次迭代currsum += numbers[k];中更改currsum,因此要检查每个新结果,您必须重置currsum。你不必在循环之前声明它,实际上你可以在把它设置为0的地方声明它。

提示:您也不必初始化startend变量,您可以使用ij

相关内容

最新更新