Atof explanation
I`m looking for explanation how this atop works:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
/* atof example: sine calculator */
#include <stdio.h> /* printf, fgets */
#include <ctype.h>
#include <math.h> /* sin */
double atof(char s[]);
int main ()
{
double n,m;
double pi=3.1415926535;
char buffer[256];
printf ("Enter degrees: ");
fgets (buffer,256,stdin);
n = atof (buffer);
m = sin (n*pi/180);
printf ("The sine of %f degrees is %f\n" , n, m);
return 0;
}
double atof(char s[])
{
double val, power;
int i, sign;
for (i = 0; isspace(s[i]); i++) //skip whitespace
;
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-')
i++;
for (val = 0.0; isdigit(s[i]); i++)
val = 10.0 * val + (s[i] - '0');
if (s[i] == '.')
i++;
for (power = 1.0; isdigit(s[i]); i++) {
val = 10.0 * val + (s[i] - '0');
power *= 10.0;
}
return sign * val / power;
}
|
Why is it that it gives me
Enter degrees: 123.445
The sine of 123.445000 degrees is 0.834415
What are you expecting as the output?
Topic archived. No new replies allowed.