Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * 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>
- /* atof: convert string s to double */
- double
- atof(char s[])
- {
- double val, power, exp, expv;
- int i, sign, expsgn;
- 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;
- }
- if (s[i] == 'e' || s[i] == 'E') {
- i++;
- expsgn = 1;
- if (s[i] == '-')
- expsgn = -1;
- if (s[i] == '-' || s[i] == '+')
- i++;
- }
- for (exp = 0.0; isdigit(s[i]); i++)
- exp = 10.0 * exp + (s[i] - '0');
- expv = 1.0;
- while (exp--) {
- expv *= 10.0;
- }
- if (expsgn == -1)
- expv = 1 / expv;
- return (sign * val / power * expv);
- }
- int
- main(int argc, char **argv) {
- double d;
- d = atof("1.332E2");
- printf("d = %lf\n", d);
- return (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment