我有這個執行,這個程序的結果是100,但正確答案是103 是任何人都知道什麼是錯在這個實現或是否有更好的辦法用於查找數組中整數的最大連續和?找到整數的最大連續總和在陣列
在此先感謝。
#include <stdio.h>
int main(void) {
int a[] = { -3, 100, -4, -2, 9, -63, -200, 55 };
int max_sum, temp_sum, i, n = 12, t;
temp_sum = max_sum = a[0];
for (i = 1; i < n; i++) {
if (a[i] > 0)
temp_sum += a[i];
else {
t = 0;
while (a[i] < 0 && i < n) {
t += a[i];
i++;
}
if (temp_sum + t > 0) {
temp_sum = temp_sum + t + a[i];
if (temp_sum > max_sum)
max_sum = temp_sum;
} else if (i < n)
temp_sum = a[i];
}
}
if (temp_sum > max_sum)
max_sum = temp_sum;
printf("Maximum Numbers is %d \n", max_sum);
return 0;
}
這裏有smt怪異的,我把你的代碼複製到CodeBlocks,結果是332? – 2012-04-10 19:48:45
這是功課嗎?你應該考慮使用遞歸。 – 2012-04-10 19:49:59
「最大連續數」是什麼意思?你怎麼能得到103? – Saphrosit 2012-04-10 19:50:20