I am currently working on a computer science project and I am stuck whilst trying to work on the final steps. It is very messy thus far, but the code basically takes the first two values given as x and y coordinates, and uses these to produce a total distance. It also then uses a third point to calculate the total uphill and downhill gradients. I have gotten these parts working correctly, however the assignment states: You should read data using scanf until EOF occurs, which can be detected by checking the return value of scanf. I am wondering how I would go about achieving this? At the moment I have the constraints of my do-while loop being that once it = EOF it will terminate, however this causes the code to terminate at any -1 present. Here is the code:
#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;
}
And given the following input:
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
Should return:
Total distance: 9.0
Maximum uphill gradient: 1.000
Maximum downhill gradient: 1.500
scanf
. If it is0
, break.EOF
is not the scanned value, but a possible return value ofscanf
: It returns the number of arguments successfully converted orEOF
when the input stream runs out. Look at the "Related" answers to the right to learn how to control loops withscanf
.EOF
should not be tested against the return value ofscanf
, because the test will fail if reading failed due to a different error