forked from Heatwave/The-C-Programming-Language-2nd-Edition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4.getfloat.c
89 lines (71 loc) · 1.36 KB
/
4.getfloat.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
#include <stdio.h>
#include <ctype.h>
#define SIZE 10
int getch(void);
void ungetch(int);
// compile with getch.c
int main()
{
int n;
double array[SIZE], getfloat(double *);
for (n = 0; n < SIZE; n++)
array[n] = 0.0;
for (n = 0; n < SIZE && getfloat(&array[n]) != EOF; n++)
;
for (n = 0; n < SIZE; n++)
printf("%g ", array[n]);
printf("\n");
return 0;
}
double getfloat(double *pn)
{
int c, sign;
double power;
while (isspace(c = getch()))
;
if (!isdigit(c) && c != EOF && c != '+' && c != '-' && c != '.') {
ungetch(c);
return 0.0;
}
sign = (c == '-') ? -1 : 1;
if (c == '+' || c == '-') {
c = getch();
if (!isdigit(c) && c != '.') {
ungetch(sign == 1 ? '+' : '-');
return 0.0;
}
}
for (*pn = 0.0; isdigit(c); c = getch())
*pn = 10.0 * *pn + (c - '0');
if (c == '.') {
c = getch();
}
for (power = 1.0; isdigit(c); c = getch()) {
*pn = 10.0 * *pn + (c - '0');
power *= 10.0;
}
int eSign = 1;
if (c == 'e' || c == 'E') {
c = getch();
if (c == '-') {
eSign = -1;
c = getch();
} else if (c == '+') {
c = getch();
}
}
double ePower = 1.0;
int eCount = 0;
for (eCount = 0; isdigit(c); c = getch())
eCount = 10.0 * eCount + (c - '0');
while (eCount-- > 0)
ePower *= 10;
*pn = *pn / power * sign;
if (eSign > 0)
*pn *= ePower;
else
*pn /= ePower;
if (c != EOF)
ungetch(c);
return c;
}