C程序的奇怪行为

时间:2014-03-30 02:27:55

标签: c

我一直在使用Windows,最近在Virtual Box上安装了Ubuntu。为了尝试Ubuntu,我写了一个简单的计算器程序。

这是怎么回事:

#include<stdio.h>
float add(float ,float ),sub(float , float ),mul(float ,float ),div(float ,float );
int main()
{
char ch;
float a,b;
printf("Enter an operator: ");
scanf("%c",&ch);
printf("Enter two values: ");
scanf("%f%f",&a,&b);
switch(ch)
{
    case '+':
        printf("The sum of %f and %f is %f\n",a,b,add(a,b));
        break;
    case '-':
        printf("The substraction of %f from %f is %f\n",a,b,sub(a,b));
        break;
    case '*':
        printf("The multiplication of %f and %f is %f\n",a,b,mul(a,b));
        break;
    case '/':
        printf("The division of %f and %f is %f\n",a,b,div(a,b));
        break;
    default:
        printf("\nEnter a valid operator: \n");
        main();
}
return 1;
}
float add(float x,float y)
{
    return (float)x + y;
}
float sub(float x,float y)
{
    return (float)x-y;
}
float mul(float x,float y)
{
    return (float) x*y;
}
float div(float x,float y)
{
    return (float) x/y;
}

当我输入无效的运算符时,它实际上应该再次读取运算符和值。但是,它没有阅读操作员就直接询问价值。这是一张图片:

Running the code

那么我做错了什么?请解释。提前谢谢!

1 个答案:

答案 0 :(得分:3)

您没有忽略输入中的换行符。

更改

scanf("%c", &ch);

scanf(" %c", &ch);

再试一次。

当您输入3<enter>时,第二个3将使用%f,但<enter>(即换行符)仍将在输入缓冲区中,并且第一个%c中的scanf()将使用此换行符。 %c中的空格将忽略输入缓冲区中的换行符。


$ ./a.out
Enter an operator: h
Enter two values: 2
3

Enter a valid operator: 
Enter an operator: +
Enter two values: 2
3
The sum of 2.000000 and 3.000000 is 5.000000
相关问题