【发布时间】:2015-11-28 15:43:22
【问题描述】:
我编写了一个代码来检查 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() 会返回 -1。 (不是反问,我很感兴趣)?
-
scanf函数的返回值是成功转换的次数,即。 arguments ,输入转换。失败时返回 -1
-
@IlanAizelmanWS 是的,但是为什么按 Ctrl + Z 会失败?
-
您在问题中提到了
scanf,但您的代码使用了scanf_s,这不是标准函数(我认为这是微软的东西?)。我认为您还假设EOF是-1,这通常不能保证是正确的(尽管它可能是在MS 的情况下,我不知道并且没有方便检查的编译器! )。scanf函数返回 分配的字段数 - 不是写入的字符 - 或EOF出错,或者如果在读取 first 字符时它得到 end-of-文件。我认为要强制文件结束条件,您必须按 Enter-Ctrl+Z-Enter,这可能是问题所在? -
@Transcendental 因为 scanf 应该得到 2 个浮点数。如果它得到 (Ctrl+Z) 它不是一个浮点数。这意味着它将返回 -1