/******************************************************************************* * K&R 4-2 * * atof extended: convert string s to double, allow for possible scientific * notation accepting e or E and an optionally signed exponent. * * program: atof_extended * by.....: yetimach * date...: 06 November 2024 * ******************************************************************************/ #include #include #define MAX 21 char gs[MAX]; void read_line(char s[], int max){ int c, i = 0; while (i < max-1 && (c = getchar()) != '\n' && c != EOF) s[i++] = c; } double atof(char s[]){ double val, power; int i, sign, e, e_sign, is_e = 0; 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; } val = sign * val / power; if (s[i] == 'e' || s[i] == 'E'){ i++; is_e = 1; } e_sign = (s[i] == '-') ? -1 : 1; if (s[i] == '+' || s[i] == '-') i++; for (e = 0; isdigit(s[i]); i++) e = 10 * e + (s[i] - '0'); e *= e_sign; if (is_e && e == 0) return 1.0 * sign; while (e < 0){ val *= 0.1; e++; } while (e-- > 0) val *= 10; return val; } int main(void) { printf("(Accepts decimal values and scientific notation, " "20 character limit)\nEnter number value: "); read_line(gs, MAX); double converted_value = atof(gs); printf("\nThe converted number is %f\n", converted_value); return 0; }