我已经在 Xcode 和在线 C 编译器中测试了我的代码,由于某种原因 Xcode 打印了一个值 1606416234,而正确的总和应该是 10。
#include <stdio.h>
int sum_array(int x[], int n);
int main(void) {
// insert code here...
printf("Hello, World!\n");
int y[4]={1,2,3,4};
printf("%d\n", sum_array(y, 4));
return 0;
}
int sum_array(int x[], int n){
int i, sum=0;
for (i= 0; i<=n; i++){
sum+=x[i];
}
return sum;
}
为什么 Xcode 给我这么大的数字?
最佳答案
你的 for
循环太远了。你需要i < n
, 不是 <=
.您正在将数组读取到未知内存中。这个额外的值可以用任何东西填充。在某些情况下,它可能是 0,这会意外地给您正确的结果,即使代码是错误的。
关于c - Xcode 给出了简单 C 数组的错误总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44269402/