我目前正在从事计算机科学项目,并且在尝试完成最后一步时遇到困难。到目前为止它非常混乱,但代码基本上将前两个值作为x和y坐标给出,并使用它们来产生总距离。然后它还使用第三个点来计算总上坡和下坡梯度。我已经让这些部件正常工作,但是分配说明:您应该使用scanf读取数据,直到发生EOF,这可以通过检查scanf的返回值来检测。 我想知道如何实现这一目标?目前我有do-while循环的约束,一旦它= EOF它将终止,但这会导致代码终止于任何-1存在。 这是代码:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(void)
{
double a;
double total;
double up;
double b;
double c;
double d;
double down;
double zc;
double yes;
double m;
double n;
double m2;
double n2;
double o;
double p;
double q;
double xc;
double yc;
int i = 1;
xc = 1000;
yc = 1000;
total = 0;
down = 0;
scanf("%lf", &c);
do
{
if (i == 1) {
a = c;
scanf ("%lf", &c);
i += 1;
}
else if (i == 2) {
b = c;
scanf ("%lf", &c);
i += 1;
}
else if (i ==3) {
d = c;
if (xc == 1000 && yc == 1000) {
i = 4;
}
else if (xc != 1000) {
i = 5;
}
}
else if (i == 4) {
if (d > zc) {
yes = d - zc;
up = yes/p;
if (up > total) {
total = up;
}
}
if (d < zc) {
yes = d - zc;
up = yes/p;
if (up < 0) {
up = up *-1;
}
if (up > down) {
down = up;
}
}
xc = b;
yc = a;
zc = d;
scanf ("%lf", &c);
i = 1;
}
else if (i == 5) {
m = (xc - b);
n = (yc - a);
m2 = m*m;
n2 = n*n;
o = m2 + n2;
p = sqrt(o);
q = q + p;
i = 4;
}
}
while (c != EOF && i <= 5);
printf ("Total distance: %.1lf\n", q);
printf ("Maximum uphill gradient: %.3lf\n", total);
printf ("Maximum downhill gradient: %.3lf\n", down);
return EXIT_SUCCESS;
}
并给出以下输入:
0.0 0.0 0.0
0.0 3.0 1.0
1.0 3.0 2.0
1.0 5.0 -1.0
4.0 5.0 -1.0
应该返回:
Total distance: 9.0
Maximum uphill gradient: 1.000
Maximum downhill gradient: 1.500
答案 0 :(得分:2)
您可以检查函数scanf()
的返回值。例如:
scanf("%d %d",&a,&b);
。
a
和b
,则会返回2
。a
,则会返回1
。int
,它将返回0
。scanf()
期间收到文件的末尾,则会返回EOF
。我希望这可以帮到你。
答案 1 :(得分:1)
您可以像这样check=scanf("%lf", &c);
存储scanf的返回值
while(check != EOF && i <= 5);
check
变量的类型必须为int。