c - 为什么它不能正确添加我的号码

标签 c loops while-loop

我正在尝试将数组中的 100 个数字相加,这是我的代码: 从 17 到 117 的数字加起来应该更多。

#include <stdio.h>
#include <stdlib.h>

int main(){
int* number = malloc(101*sizeof(int));
int num = 0;    

while (num != 101){
    number[num] = 17 + num;
    num = num + 1;
};


num = 0;

while(num != 101){
    printf(" %d \n", number[num]);
    num = num + 1;
}

num = 0;
int sum = 0;
while (num != 101){
    number[num] = 17;
    sum = sum + number[num];
    num = num + 1;

}

printf(" %d \n ", sum );

return 0;
}

底部打印语句给出的值为 1717

最佳答案

while (num != 101){
    number[num] = 17;
    sum = sum + number[num];

删除将所有内容重置为 17 的第二行

关于c - 为什么它不能正确添加我的号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35165399/

相关文章:

python - 如何解决 Python 中的 StopIteration 错误?

c - 如何将包含作为命令行参数传递的整数的字符串转换为整数数组

C文件比较

php - 确定 foreach 循环在其最终迭代中的最简单方法

python - 在 Python 中解包的多个 for 循环迭代器

Java 条件困惑? (初学者)

python - 如何在 Python 的 while 测试中增加计数器

c - 为什么在 Linux 中使用 select

c++ - 文件系统中的数据结构存储

c# - Try-Catch 语句结束 While 循环读取 C# 中的 XML 文件