gpt4 book ai didi

c - 相加直到遇到负数

转载 作者:行者123 更新时间:2023-12-02 00:03:34 24 4
gpt4 key购买 nike

我正在尝试创建一个程序,让用户输入数字(最大条目>10^6)直到遇到负数。我已经尝试了很多版本,但它们要么没有记录输入的负值,要么崩溃。

这是我目前所在的位置:

#include <stdio.h>

#define HIGHEST 999999
int main(){
int i=0, entry, sum=0;
while(i<HIGHEST){
scanf("%i", entry);
if(entry>0){
sum+=entry;
}
else{
i=HIGHEST;
}
i++;
}
printf("Sum: %i", sum);
system("pause");
}

最佳答案

您的问题出在这一行:

scanf("%i", entry);

应该是:

scanf("%i", &entry);

您需要传入将存储扫描值的整数变量的地址。自从条目从未初始化,它只是充满了垃圾/内存中的任何内容,而不是输入的值。看这个reference ,其中指出,

  "Depending on the format string, the function may expect a sequence of additional arguments,     
each containing a pointer to allocated storage where the interpretation of the extracted
characters is stored with the appropriate type"

关于c - 相加直到遇到负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19884214/

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