【发布时间】:2024-01-19 11:18:02
【问题描述】:
在这个程序中,num1 值在 if-else 条件内变为零。我得到了错误的答案,因为变量自动变为 0。为什么会这样?如果我将 num1 设为 4,将 num2 设为 3。我得到的附加值是 3,它应该是 7 对。请帮忙解决
#include<stdio.h>
void main()
{
int num1, num2, answer;
char type;
printf("Enter num1\n");
scanf("%d",&num1);
printf("Enter num2\n");
scanf("%d",&num2);
printf("type a for addition or s for subtraction\n");
scanf("%s",&type);
if(type == 'a')
{
answer = num1 + num2;
printf("answer is %d \n",answer);
}
else if(type == 's')
{
answer = num1 - num2;
printf("answer is %d \n",answer);
}
else
{
printf("enter a or s");
}
}
【问题讨论】:
-
scanf("%s",&type);调用 未定义的行为 - 您正在尝试将一个以 null 结尾的字节字符串读入单个字符 -
使用
scanf(" %c",&type);。%c之前的空格会跳过可选的空格。 -
add和sub在 if else 语句中未定义。你的代码是如何编译的?
标签: c if-statement char