From 71f25e917429698f119dad2939d9cc585183e332 Mon Sep 17 00:00:00 2001 From: Steven Schronk Date: Tue, 15 Dec 2009 20:46:09 -0600 Subject: [PATCH] Completed tutorial for 4-2. Converts string of chars into long double. --- ex_4-2.c | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 58 insertions(+), 12 deletions(-) diff --git a/ex_4-2.c b/ex_4-2.c index ff8d1fc..a42325b 100644 --- a/ex_4-2.c +++ b/ex_4-2.c @@ -1,42 +1,88 @@ #include #include + /* -Add support for scientific notation. +Converts string of char into a double. +Supports scientific notation, signed exponents. -123.45e-6 -123.45E6 --123.45e56 +Warning: very large or small numbers exibit rounding errors. */ double atof(char s[]) { - double val, power; - int i, sign; - for(i=0; isspace(s[i]); i++) /* skip spaces */ + long double val, power, expower; + int i, sign, exsign; + for(i=0; isspace(s[i]); i++) // skip spaces ; sign = (s[i] == '-') ? -1 : 1; // mark sign for number - if(s[i] == '+' || s[i] == '-') // skip over signs + while(!isdigit(s[i])) // skip over signs and non numbers, dollar signs i++; - for(val = 0.0; isdigit(s[i]); i++) + + val = 0.0; + while(isdigit(s[i])) // calc val of nums before decimal + { val = 10.0 * val + (s[i] - '0'); + i++; + } + if(s[i] == '.') // skip over decimals i++; - for(power = 1.0; isdigit(s[i]); i++) + power = 1.0; + while(isdigit(s[i])) // calc val of nums after decimal { val = 10.0 * val + (s[i] - '0'); power *= 10.0; + i++; } - return sign * val / power; + + val = sign * val / power; + + // check for exponent + if(s[i] == 'e' || s[i] == 'E') + { + ++i; // move past e or E + exsign = (s[i] == '-') ? -1 : 1; // mark sign for number + while(!isdigit(s[i])) // skip over sign(s) + i++; + + expower = 0.0; + while(isdigit(s[i])) + { + expower = 10.0 * expower + (s[i] - '0'); + ++i; + } + } + + /* cannot get pow() to work in math.h ... improvising :) */ + if(exsign == 1) + { + while(expower > 0) { val = val * 10; --expower; } + } else { + while(expower > 0) { val = val / 10; --expower; } + } + return val; } int main() { - char s[] = "-10928473.25"; + char s[] = "-123.456e-7"; double ans = atof(s); printf("%f\n", ans); + + char r[] = "123.45e-6"; + ans = atof(r); + printf("%f\n", ans); + + char t[] = "123.45E6"; + ans = atof(t); + printf("%f\n", ans); + + char u[] = "-123.45e56"; + ans = atof(u); + printf("%f\n", ans); return 0; } -- 2.11.4.GIT