[英]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.