[英]Why printf() is not used when scanf returns negative number?
我写了一个代码,检查scanf()返回负数的时间,例如,如果我按“ Ctrl + Z”,它应该退出while循环并返回printf(“ Finish!”),但它不会打印“完!” 有人可以看看吗?
#include <stdio.h>
#include <conio.h>
#include <math.h>
#define G 9.81
float Height(float speed, float angle, float time);
float Horizontal(float speed, float angle, float time);
void main()
{
float speed;
float angle;
float time = 0.1;
float height = 0;
float horizontal = 0;
int res = 0;
printf("Enter v <0.0 - 100.0 m/s> and a <0-90 degrees>: ");
res = scanf_s("%f %f", &speed, &angle);
while (res != -1)
{
for (time = 0.1; height >= 0; time += 0.1)
{
printf("Time: %.1f .... H = %.2f S = %.2f \n", time, horizontal = Horizontal(speed, angle, time), height = Height(speed, angle, time));
}
height = 0;
printf("Fallen!\n");
printf("Enter v <0.0 - 100.0 m/s> and a <0-90 degrees>: ");
res = scanf_s("%f %f", &speed, &angle);
}
printf("\nFinish!\n");
getch();
}
float Height(float speed, float angle, float time)
{
float height;
angle = ((3.14 / 180) * angle);
height = (speed * sin(angle) * time) - ((G*time*time) / 2);
return height;
}
float Horizontal(float speed, float angle, float time)
{
float horizontal;
angle = ((3.14 / 180) * angle);
horizontal = (speed * cos(angle)) * time;
return horizontal;
}
我在Windows上使用Visual Studio(C语言)。
这是scanf()的参考: http : //www.cplusplus.com/reference/cstdio/scanf/
当scanf()遇到文件末尾时(这是控制台上ctrl + z的通常含义),它不是匹配的错误:仅一部分预期项可以读取。
使您的时间使用> 0而不是> = 0。
确保在Ctrl + Z之后按Enter。 默认情况下,终端输入是行缓冲的,遇到换行符时将其传递给程序。
另外,很可能您是在单独的终端窗口中运行该程序,该窗口在程序退出时关闭。 这将解释对getch();
最后,要能够看到输出,然后用按键关闭窗口。
默认情况下,当到达换行符\\n
时,将缓冲printf
并将输出写入终端。 当程序退出时( exit
调用或main
返回),缓冲区也被刷新。 就您而言,按一下键后将打印出来,由于窗口关闭,因此您可能看不到它。
要解决此问题,请在末尾添加换行符:
printf("\nFinish!\n");
我相信它应该起作用。 即使在> =的时间内。 可以使用普通的scanf()在Unix上正常工作。
您正在使用什么IDE和编译器? 您是否直接通过cmd.exe运行此程序? 我建议检查Windows 7上的EOF是否有问题。另外,如其他答案所述,请添加:
printf("\nFinish!\n");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.