summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSadeep Madurange <smadurange@users.noreply.github.com>2021-12-05 12:20:24 +0800
committerSadeep Madurange <smadurange@users.noreply.github.com>2021-12-05 12:20:24 +0800
commitf4a422e2d69731be5eabfcb1a6ab722aadb84322 (patch)
tree6af4bcbb9f6f3c038e569e2056057d3d244c0080
parentda633eb55be20b86a004a172ce5fe720ae5e8de9 (diff)
downloadk&r-exercises-f4a422e2d69731be5eabfcb1a6ab722aadb84322.tar.gz
4.2
-rw-r--r--4/2.c48
1 files changed, 48 insertions, 0 deletions
diff --git a/4/2.c b/4/2.c
new file mode 100644
index 0000000..0f842e8
--- /dev/null
+++ b/4/2.c
@@ -0,0 +1,48 @@
+#include <ctype.h>
+#include <stdio.h>
+
+#define MAXLEN 1000
+
+/* converts string to numeric representation of doubles */
+double atof(char s[]);
+
+int main(int argc, char *argv[]) {
+ int i, c;
+ char s[MAXLEN];
+
+ printf("input: ");
+
+ for (i = 0; i < MAXLEN - 1 && (c = getchar()) != '\n' && c != EOF; i++)
+ s[i] = c;
+ s[i] = 0;
+
+ printf("numeric: %f\n", atof(s));
+
+ return 0;
+}
+
+double atof(char s[]) {
+ int i, sign;
+ double val, power;
+
+ 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;
+ }
+
+ return sign * val / power;
+} \ No newline at end of file