Added example cbd_rand_dist. Generates random numbers and displays distribution.
[C-Programming-Examples.git] / ex_4-2.c
bloba42325bdc4fe70c932ddb0b6ec5a8ce30a9d2a05
1 #include <stdio.h>
2 #include <ctype.h>
4 /*
6 Converts string of char into a double.
7 Supports scientific notation, signed exponents.
9 Warning: very large or small numbers exibit rounding errors.
13 double atof(char s[])
15 long double val, power, expower;
16 int i, sign, exsign;
17 for(i=0; isspace(s[i]); i++) // skip spaces
20 sign = (s[i] == '-') ? -1 : 1; // mark sign for number
21 while(!isdigit(s[i])) // skip over signs and non numbers, dollar signs
22 i++;
24 val = 0.0;
25 while(isdigit(s[i])) // calc val of nums before decimal
27 val = 10.0 * val + (s[i] - '0');
28 i++;
31 if(s[i] == '.') // skip over decimals
32 i++;
34 power = 1.0;
35 while(isdigit(s[i])) // calc val of nums after decimal
37 val = 10.0 * val + (s[i] - '0');
38 power *= 10.0;
39 i++;
42 val = sign * val / power;
44 // check for exponent
45 if(s[i] == 'e' || s[i] == 'E')
47 ++i; // move past e or E
48 exsign = (s[i] == '-') ? -1 : 1; // mark sign for number
49 while(!isdigit(s[i])) // skip over sign(s)
50 i++;
52 expower = 0.0;
53 while(isdigit(s[i]))
55 expower = 10.0 * expower + (s[i] - '0');
56 ++i;
60 /* cannot get pow() to work in math.h ... improvising :) */
61 if(exsign == 1)
63 while(expower > 0) { val = val * 10; --expower; }
64 } else {
65 while(expower > 0) { val = val / 10; --expower; }
67 return val;
70 int main()
72 char s[] = "-123.456e-7";
73 double ans = atof(s);
74 printf("%f\n", ans);
76 char r[] = "123.45e-6";
77 ans = atof(r);
78 printf("%f\n", ans);
80 char t[] = "123.45E6";
81 ans = atof(t);
82 printf("%f\n", ans);
84 char u[] = "-123.45e56";
85 ans = atof(u);
86 printf("%f\n", ans);
87 return 0;