Created
November 23, 2009 08:17
-
-
Save shaobin0604/240964 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Exercise 4-2. 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 <stdio.h> | |
#include <ctype.h> | |
#define EPSILON 0.000001 | |
int float_equal(double arg0, double arg1); | |
double atof(char s[]); | |
int main(void) | |
{ | |
char s[] = "123.45e-6"; | |
double r = 123.45e-6; | |
double a = -1; | |
a = atof(s); | |
printf("atof(%s) = %.10f\n", s, a); | |
if (float_equal(a, r)) | |
printf("assert success.\n"); | |
else | |
printf("assert fail.\n"); | |
return 0; | |
} | |
int float_equal(double arg0, double arg1) | |
{ | |
return fabs(arg0 - arg1) < EPSILON; | |
} | |
double atof(char s[]) | |
{ | |
double val, power; | |
int i, sign, exp; | |
for (i = 0; isspace(s[i]); i++) /* skip white space */ | |
; | |
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; | |
} | |
val = sign * val / power; | |
if (s[i] == 'e' || s[i] == 'E') | |
{ | |
sign = (s[++i] == '-') ? -1 : 1; | |
if (s[i] == '+' || s[i] == '-') | |
i++; | |
for (exp = 0; isdigit(s[i]); i++) | |
exp = 10 * exp + (s[i] - '0'); | |
if (sign == 1) | |
while (exp-- > 0) | |
val *= 10; | |
else | |
while (exp-- > 0) | |
val /= 10; | |
} | |
return val; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment