我写了这段简单的代码(它实际上根据输入的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));
}
}
Run Code Online (Sandbox Code Playgroud)
*但是*一旦我将排列更改为以下内容,编译器会询问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));
}
}
Run Code Online (Sandbox Code Playgroud)
这是因为,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];
Run Code Online (Sandbox Code Playgroud)