summaryrefslogtreecommitdiff
path: root/four/atof.c
diff options
context:
space:
mode:
Diffstat (limited to 'four/atof.c')
-rw-r--r--four/atof.c59
1 files changed, 59 insertions, 0 deletions
diff --git a/four/atof.c b/four/atof.c
new file mode 100644
index 0000000..86bd651
--- /dev/null
+++ b/four/atof.c
@@ -0,0 +1,59 @@
+#include <stdio.h>
+#include <ctype.h>
+#include <math.h>
+
+#define MAXLINE 128
+
+int
+get_line(char s[], int lim)
+{
+ int c, i;
+ i = 0;
+ while (--lim > 0 && (c = getchar()) != EOF && c != '\n') {
+ s[i++] = c;
+ }
+ if (c == '\n') {
+ s[i++] = c;
+ }
+ s[i] = '\0';
+ return i;
+}
+
+/* convert string to double-precision floating point */
+double
+atof(char s[])
+{
+ double val, power;
+ int i, sign;
+ for (i = 0; isspace(s[i]); ++i);
+ 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.0;
+ }
+ if (s[i] == 'e' || s[i] == 'E') {
+ return sign * val / power * pow(10, s[++i] - '0');
+ }
+ return sign * val / power;
+}
+
+int
+main()
+{
+ double sum;
+ char line[MAXLINE];
+ sum = 0;
+ while (get_line(line, MAXLINE) > 0) {
+ printf("\t%g\n", sum += atof(line));
+ }
+ return 0;
+}