Page 73
Extend atof
to handle scientific notation of the form 123.45e-6
where a
floating-point number may be followed by e or E and an optionally signed exponent.
#include <ctype.h>
#include <stdio.h>
double atof(char s[]);
int main()
{
printf("%f", atof("123.45e-3"));
}
double atof(char s[])
{
double val, power, exponent;
int i, sign, expsign;
for (i = 0; isspace(s[i]); i++)
;
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;
}
if (s[i] == 'e') {
i++;
}
expsign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-') {
i++;
}
for (exponent = 0.0; isdigit(s[i]); i++) {
exponent = exponent * 10.0 + (s[i] - '0');
}
for (int j = 0; j < exponent; j++) {
power = expsign > 0 ? power / 10 : power * 10;
}
return sign * val / power;
}