我是c语言新手,当我用c语言编写一个基本程序时,它显示了两个答案..1)当我分别声明和初始化变量时2)当我在同一行中声明和初始化变量时。可以任何请告诉我我的错误?
#include <stdio.h>
#include <stdlib.h>
void sum()
{
printf("enter the numbers to be added\n");
int x=scanf("%d",&x);
int y=scanf("%d",&y);
int sum=(x+y);
printf("the sum of two numbers is %d\n",sum);
}
int main()
{
printf("welcome to addition calculator\n");
sum();
return 0;
}
当我给出 3 和 4 作为输入时,我得到 2 作为答案
最佳答案
scanf("%d", &x)
会将读取到的数字存储到 x
中。它将返回成功读取字段的数量(在您的情况下为 1
)。如果您随后将该返回值分配给 x
,则会覆盖用户使用该 1
输入的任何内容。 1 + 1
产生 2
。
解决方案:
int x;
int y;
scanf("%d",&x);
scanf("%d",&y);
正如 David 在评论中提醒的那样,您可能需要检查所有字段是否已成功读取。例如,在您的情况下,如果您输入非数字,scanf
将不会成功解析 %d
字段,并将返回 0
。您可以测试此结果以确保用户做了他们应该做的事情:
int x;
int y;
while (scanf("%d", &x) != 1) {
printf("Enter a NUMBER, you illiterate buffoon!\n");
}
while (scanf("%d", &y) != 1) {
printf("Enter a NUMBER! You managed with %d, how is this suddenly hard now?!\n", x);
}
关于c - C语言编程中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54412757/