Blob


1 /*
2 * Exercise 4-2. Extend atof to handle scientific notation of the form
3 *
4 * 123.45e-6
5 *
6 * where a floating point number may be followed by e or E and an optionally
7 * signed exponent.
8 */
10 #include <stdio.h>
11 #include <ctype.h>
12 #include <math.h>
14 #define MAXLINE 100
16 /* rudimentary calculator */
18 double pow(double x, double y);
20 int main() {
21 double atof(char []);
22 char line[MAXLINE];
23 int getlin(char line[], int max);
25 while (getlin(line, MAXLINE) > 0)
26 printf("\t%f\n", atof(line));
27 return 0;
28 }
30 /* getlin: get line into s, return length */
31 int getlin(char s[], int lim) {
32 int c, i;
33 i = 0;
34 while (--lim > 0 && (c=getchar()) != EOF && c != '\n')
35 s[i++] = c;
36 if (c == '\n')
37 s[i++] = c;
38 s[i] = '\0';
39 return i;
40 }
42 /* atof: convert string s to double */
43 double atof(char s[]) {
44 double val, power;
45 int i, sign, expsign, exp;
47 for (i = 0; isspace(s[i]); i++) /* skip white space */
48 ;
49 sign = (s[i] == '-') ? -1 : 1;
50 if (s[i] == '+' || s[i] == '-')
51 i++;
52 for (val = 0.0; isdigit(s[i]); i++)
53 val = 10.0 * val + (s[i] - '0');
54 if (s[i] == '.')
55 i++;
56 for (power = 1.0; isdigit(s[i]); i++) {
57 val = 10.0 * val + (s[i] - '0');
58 power *= 10.0;
59 }
60 if (s[i] == 'e' || s[i] == 'E') {
61 i++;
62 expsign = (s[i] == '-') ? -1 : 1;
63 if (s[i] == '+' || s[i] == '-')
64 i++;
65 for (exp = 0; isdigit(s[i]); i++)
66 exp = 10 * exp + (s[i] - '0');
67 } else {
68 exp = 0;
69 expsign = 1;
70 }
71 return sign * val * pow(10,expsign*exp) / power;
72 }
74 int atoi(char s[]) {
75 double atof(char s[]);
76 return (int) atof(s);
77 }