diff options
author | sinanmohd <pcmsinan@gmail.com> | 2022-06-06 13:24:34 +0530 |
---|---|---|
committer | sinanmohd <pcmsinan@gmail.com> | 2022-06-06 13:24:34 +0530 |
commit | 31a036f54543af5c6d9cabea58b021620e888035 (patch) | |
tree | e2b3f5237e79a7d729ae10b51a7eb7e02c689713 /4.2.c | |
parent | f690af3d466efd4d1ff45f0e79a0288be4f4c915 (diff) |
added 4.1 and 4.2
Diffstat (limited to '4.2.c')
-rw-r--r-- | 4.2.c | 80 |
1 files changed, 80 insertions, 0 deletions
@@ -0,0 +1,80 @@ +#include <stdio.h> +#include <ctype.h> + +#define MAXLEN 64 + +int sneed_getline(char str[], int max); +double atof(const char str[]); + +int +main(void) +{ + char str[MAXLEN]; + + while (sneed_getline(str, MAXLEN) > 0) + printf("%f\n\n", atof(str)); + + return 0; +} + +int +sneed_getline(char str[], int max) +{ + int i; + char input; + + for (i = 0; i < max && (input = getchar()) != EOF && input != '\n'; i++) + str[i] = input; + + if (i < max && input != '\n') + str[i++] = '\n'; + + str[i] = '\0'; + + return i; +} + +double +atof(const char str[]) +{ + int i, sign, e_sign, j; + double val, power, e_power; + + for (i = 0; isspace(str[i]); i++) + ; + sign = (str[i] == '-') ? -1 : 1; + + if (str[i] == '-' || str[i] == '+') + i++; + + for(val = 0.0; isdigit(str[i]); i++) + val = val * 10.0 + (str[i] - '0'); + + if (str[i] == '.') + i++; + + for(power = 1.0; isdigit(str[i]); i++) { + val = 10 * val + (str[i] - '0'); + power *= 10.0; + } + + if (str[i] == 'e' || str[i] == 'E') + i++; + + e_sign = (str[i] == '-') ? -1 : 1; + + if (str[i] == '-' || str[i] == '+') + i++; + + for (e_power = 0.0; isdigit(str[i]); i++) + e_power = e_power * 10 + (str[i] - '0'); + + if (e_sign < 0) + for (j = 0; j < e_power; j++) + power *= 10; + else + for (j = 0; j < e_power; j++) + power /= 10; + + return (sign * val / power); +} |