Write getfloat, the floating-point analog of getint. What types does getfloat return as its function value?
gefloat
would also return an integer value.
Here is my solution:
int getfloat(double *pf) {
int c, sign;
double power;
while(isspace(c = getch()))
;
if(!isdigit(c) && c != EOF && c != '-' && c != '+' && c != '.') {
ungetch(c); /* push the number back in buffer */
return 0; /* not a valid number */
}
sign = (c == '-') ? -1 : 1;
if(c == '-' || c == '+')
c = getch();
if(!isdigit(c) && c != '.') {
ungetch(c);
return 0; /* not a number */
}
for(*pf = 0.0; isdigit(c); c = getch())
*pf = *pf * 10 + (c - '0');
if(c == '.')
c = getch();
for(power = 1.0; isdigit(c); c = getch()) {
*pf = *pf * 10 + (c - '0');
power *= 10;
}
*pf *= sign;
*pf /= power; /* moving the decimal point */
if(c != EOF)
ungetch(c);
return c; /* it actually returns the value of the charachter that caused the break of the second for */
}
I have changed the type of the parameter *pf
to double
, thus it will handle the floating point represenation of a number. The condition of the first if-statement
was extended, such that it will not push back in to the buffer a decimal point.
The second for
computes the decimal part of the number, storing the number of places that the decimal point should pe moved in the variable power
. If there is no decimal part, power
will have the value 1
- thus, nothing will change if I devide *pf
by power
when power
is 1
.