#include<stdio.h>
int main()
{
int num1 , num2 , result ;
char c ;
printf("Enter the numbers and operation \n");
scanf("%d%d",&num1 , &num2);
printf("Enter the sign :\n");
scanf("%c" , c);
if(c == '+')
{
result = num1 + num2 ;
printf("%d \n",result);
}
else if (c == '-')
{
result = num1 - num2 ;
printf("%d \n",result);
}
else if(c == '*')
{
result = num1 * num2 ;
printf("%d \n",result);
}
else if (c == '/')
{
result = num1 / num2 ;
printf("%d \n",result);
}
else if (c == '%')
{
result = num1 % num2 ;
printf("%d \n",result);
}
else
{
printf("Error \n");
}
getchar();
}
答案 0 :(得分:3)
问题是当您输入数字时按“ Enter”键时,字符'\r'
将存储在字符c
中,从而引发else
语句。
有两种解决方案不存储该\r
字符
解决方案1:
printf("Enter the numbers and operation \n");
scanf("%d%d%*c",&num1 , &num2); // %*c skips a character to write
printf("Enter the sign :\n");
scanf("%c" , &c); //&c to store scanf in your char c
if(...)
解决方案2:
printf("Enter the numbers and operation \n");
scanf("%d%d",&num1 , &num2);
printf("Enter the sign :\n");
scanf(" %c" , &c); // the space tells scanf to discard any of the whitespaces
if(...)