2012-02-10 125 views
1

我写了这段简单的代码(它实际上是根据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)); 
} 
} 

* *只要我改变安排如下编译器询问x的值,并跳过scanf函数对焦炭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)); 
} 
} 
+0

'无效的主要()'是不是入口点的正确签名。你正在寻找'int main(void)'。 – 2012-02-10 17:58:38

+0

但前一个运行良好......? – bluedroid 2012-02-10 18:01:41

+0

即使使用int main()它也会跳过第二个scanf ... – bluedroid 2012-02-10 18:04:35

回答

5

这是因为scanf%c接受一个字符 - 任何字符,包括'\n'。当你在输入你的浮点值后点击“返回”按钮时,I/O系统给你浮动,并缓冲“返回”字符。当您拨打scanf%c时,角色已经在那里,所以它马上给你。

为了解决这个问题,创建一个字符串缓冲区,调用scanf%s,并使用字符串的第一个字符为您选择的性格,就像这样:

char buf[32]; 
printf("\nPress s or S for sin(x); c or C for cos(x); t or T for tan(x)\n\n"); 
scanf("%30s", buf); 
T = buf[0];