From f4a422e2d69731be5eabfcb1a6ab722aadb84322 Mon Sep 17 00:00:00 2001 From: Sadeep Madurange Date: Sun, 5 Dec 2021 12:20:24 +0800 Subject: 4.2 --- 4/2.c | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 4/2.c (limited to '4') 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 +#include + +#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 -- cgit v1.2.3