gpt4 book ai didi

c - 为什么 scanf 返回负数时不使用 printf()?

转载 作者:太空宇宙 更新时间:2023-11-04 03:34:04 25 4
gpt4 key购买 nike

我写了一段代码来检查 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 的通常含义)时,这不是匹配错误:它只是可以读取预期项目的一部分。

让你的 while 使用 >0 而不是 >=0。

关于c - 为什么 scanf 返回负数时不使用 printf()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33973176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com