gpt4 book ai didi

c - 查找数组中整数的最大连续和

转载 作者:太空狗 更新时间:2023-10-29 15:51:11 26 4
gpt4 key购买 nike

我有这个实现,这个程序的结果是 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;
}

最佳答案

您没有使用正确的索引:

演示请看这里:http://codepad.org/wbXZY5zP

int max_sum, temp_sum, i, n = 8, t;
temp_sum = max_sum = a[0];
for (i = 0; i < n; i++) {
(...)
}

关于c - 查找数组中整数的最大连续和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10095375/

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