编译时编译器跳过语句?

时间:2012-02-10 17:54:25

标签: c

我写了这段简单的代码(它实际上根据输入的s,c或t来计算x的正弦,余弦或正切值),这种方法很好,直到我试图改变语句的顺序为止... ..这个工作正常......

#include<stdio.h>
#include<math.h>
void main()
{
char T;
float x;
printf("\nPress s or S for sin(x); c or C for cos(x); t or T for tan(x)\n\n");
scanf("%c", &T);
printf("Enter the value of x: ");
scanf("%f",&x);

if(T=='s'||T=='S')
{
    printf("sin(x) = %f", sin(x));
}
else if(T=='c'||T=='C')
{
    printf("cos(x) = %f", cos(x));
}
else if(T=='t'||T=='T')
{
    printf("tan(x) = %f", tan(x));
}
}

* BUT *一旦我将配置更改为以下内容,编译器会询问x的值并跳过scanf for char T并且不返回任何内容......任何人都可以解释这里发生了什么???

#include<stdio.h>
#include<math.h>
void main()
{
char T;
float x;

printf("Enter the value of x: ");
scanf("%f",&x);
printf("\nPress s or S for sin(x); c or C for cos(x); t or T for tan(x)\n\n");
scanf("%c", &T);
if(T=='s'||T=='S')
{
    printf("sin(x) = %f", sin(x));
}
else if(T=='c'||T=='C')
{
    printf("cos(x) = %f", cos(x));
}
else if(T=='t'||T=='T')
{
    printf("tan(x) = %f", tan(x));
}
}

1 个答案:

答案 0 :(得分:5)

这是因为scanf的{​​{1}}只占用一个字符 - 任何字符,包括%c。当您在输入浮点值后点击“返回”按钮时,I / O系统会为您提供浮点数,并缓冲“返回”字符。当您使用'\n'致电scanf时,该角色已经存在,因此它会立即发送给您。

要解决此问题,请为字符串创建缓冲区,使用%c调用scanf,并使用字符串的第一个字符作为选择器字符,如下所示:

%s