我已经编写了这段代码,但没有得到输出,任何人都可以帮助我解决这个问题吗?

时间:2018-06-22 09:42:16

标签: c

#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();

}

1 个答案:

答案 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(...)