forked from jhpy1024/CProgrammingLanguageExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise_4-2.c
93 lines (73 loc) · 2.07 KB
/
exercise_4-2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <math.h>
#include <ctype.h>
#include <stdio.h>
/* Assumes that the string is correctly formed. */
double atof(char s[])
{
double value = 0.0;
double fractional_power = 1.0;
int sign = 1;
int str_index = 0;
double power_of_ten = 0.0;
for (str_index = 0; isspace(s[str_index]); ++str_index)
{
/* Skip any whitespace. */
}
sign = (s[str_index] == '-' ? -1 : 1);
if (s[str_index] == '-' || s[str_index] == '+')
{
++str_index;
}
for (value = 0.0; isdigit(s[str_index]); ++str_index)
{
value = value * 10.0 + (s[str_index] - '0');
}
/* TODO: Remove duplication of this code. */
if (s[str_index] == 'e' || s[str_index] == 'E')
{
++str_index;
int power_of_ten_sign = (s[str_index] == '-' ? -1 : 1);
if (s[str_index] == '+' || s[str_index] == '-')
{
++str_index;
}
for (power_of_ten = 0.0; isdigit(s[str_index]); ++str_index)
{
power_of_ten = power_of_ten * 10.0 + (s[str_index] - '0');
}
power_of_ten *= power_of_ten_sign;
}
if (s[str_index] == '.')
{
++str_index;
for (fractional_power = 1.0; isdigit(s[str_index]); ++str_index)
{
value = value * 10.0 + (s[str_index] - '0');
fractional_power *= 10.0;
}
}
if (s[str_index] == 'e' || s[str_index] == 'E')
{
++str_index;
int power_of_ten_sign = (s[str_index] == '-' ? -1 : 1);
if (s[str_index] == '+' || s[str_index] == '-')
{
++str_index;
}
for (power_of_ten = 0.0; isdigit(s[str_index]); ++str_index)
{
power_of_ten = power_of_ten * 10.0 + (s[str_index] - '0');
}
power_of_ten *= power_of_ten_sign;
}
return (sign * value / fractional_power) * pow(10.0, power_of_ten);
}
int main()
{
printf("%f\n", atof("0.2e3"));
printf("%f\n", atof("1.04"));
printf("%f\n", atof("0e41"));
printf("%f\n", atof("7e2"));
printf("%f\n", atof("1e-1"));
return 0;
}