gpt4 book ai didi

c - 尝试使用 scanf 读取数字时程序崩溃

转载 作者:太空宇宙 更新时间:2023-11-04 08:41:10 25 4
gpt4 key购买 nike

当我运行这段代码时,会出现这样的消息。Project.exe 已停止工作

我的一些其他代码可以工作,但这似乎会引发错误。

enter image description here

#include<stdio.h>
#include<conio.h>

void main()
{
int n1, n2, sum;

puts("first number");
scanf("%d", n1);
fflush(stdin);
puts("second number");
scanf("%d", n2);
sum = n1 + n2;

printf("%d + %d = %d", n1, n2, sum);

getch();

}

我基本上想添加两个数字。

最佳答案

scanf 获取它存储输入值的变量的地址。您需要将 scanf 调用更改为

scanf("%d", &n1);
scanf("%d", &n2);
// ^ note the & operator

另请注意,在输入流上调用 fflush 是未定义的行为。所以,fflush(stdin) 是不正确的。您需要手动读取并丢弃 stdin 流中剩余的无关输入。

关于c - 尝试使用 scanf 读取数字时程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23516761/

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