Skip to content

Commit 74bcd57

Browse files
committed
simplify code
1 parent 49ed777 commit 74bcd57

File tree

1 file changed

+25
-24
lines changed

1 file changed

+25
-24
lines changed

chapter04/4-2.c

+25-24
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,71 @@
11
/*
22
* Exercise 4-2. Extend atof to handle scientific notation of the form
3-
* 123.45e-6
3+
*
4+
* 123.45e-6
5+
*
46
* where a floating-point number may be followed by e or E and an optionally
5-
* signed exponent.
7+
* signed exponent.
8+
*
69
* By Faisal Saadatmand
710
*/
811

912
#include <stdio.h>
1013
#include <ctype.h>
11-
#include <math.h>
1214

1315
/* functions */
1416
double atof(char []);
1517

1618
/* atof: convert string s to double */
1719
double atof(char s[])
1820
{
19-
int i, sign, expSign;
21+
int i, sign, expSign;
2022
double val, power, exponent;
2123

22-
for (i = 0; isspace(s[i]); ++i) /* skip whitespace */
24+
for (i = 0; isspace(s[i]); ++i) /* skip whitespace */
2325
;
2426

2527
sign = (s[i] == '-') ? -1 : 1;
2628
if (s[i] == '+' || s[i] == '-')
2729
++i;
2830

29-
for (val = 0.0; isdigit(s[i]); i++)
31+
for (val = 0.0; isdigit(s[i]); ++i)
3032
val = 10.0 * val + (s[i] - '0');
3133

3234
if (s[i] == '.')
33-
i++;
35+
++i;
3436

35-
for (power = 1.0; isdigit(s[i]); i++) {
37+
for (power = 1.0; isdigit(s[i]); ++i) {
3638
val = 10.0 * val + (s[i] - '0');
3739
power *= 10.0;
3840
}
3941

40-
if (s[i] != '\0') { /* handle scientific notation */
41-
if (s[i] == 'e' || s[i] == 'E')
42-
++i;
43-
else
44-
return -1;
42+
if (tolower(s[i]) == 'e') /* handle scientific notation */
43+
++i;
4544

46-
expSign = (s[i] == '-') ? -1 : 1; /* record the exponent sign */
47-
if (s[i] == '+' || s[i] == '-')
48-
++i;
45+
expSign = (s[i] == '-') ? -1 : 1; /* record exponent's sign */
46+
if (s[i] == '+' || s[i] == '-')
47+
++i;
4948

50-
for (exponent = 0.0; isdigit(s[i]); i++) /* extract the exponent */
51-
exponent = 10.0 * exponent + (s[i] - '0');
49+
for (exponent = 0.0; isdigit(s[i]); i++) /* extract the exponent */
50+
exponent = 10.0 * exponent + (s[i] - '0');
5251

53-
return (sign * val / power) * pow(10, expSign * exponent);
52+
while (exponent-- != 0) /* adjust power according to exponent */
53+
power = (expSign > 0) ? power / 10: power * 10;
5454

55-
} else
56-
return sign * val / power;
55+
return sign * val / power;
5756
}
5857

5958
int main(void)
6059
{
61-
char number[64] = { "123.45" };
62-
char number2[64] = { "123.45e-6" };
63-
char number3[64] = { "123.45e+6" };
60+
char number[] = "123.45";
61+
char number2[] = "123.45e-6";
62+
char number3[] = "123.45e+6";
63+
char number4[] = "-123.45E+6";
6464

6565
printf("%f\n", atof(number));
6666
printf("%f\n", atof(number2));
6767
printf("%f\n", atof(number3));
68+
printf("%f\n", atof(number4));
6869

6970
return 0;
7071
}

0 commit comments

Comments
 (0)