khalfella

ansi_c_pg067_ch04_ex02.c

Jan 1st, 2015
274
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. /*
  2. * Exercise 4-2.
  3. * Extend atof to handle scientific notation of the form 123.45e-6 where a
  4. * floating-point number may be followed by e or E and an optionally signed
  5. * exponent.
  6. */
  7.  
  8.  
  9.  
  10. #include <stdio.h>
  11. #include <ctype.h>
  12.  
  13. /* atof: convert string s to double */
  14. double
  15. atof(char s[])
  16. {
  17. double val, power, exp, expv;
  18. int i, sign, expsgn;
  19. for (i = 0; isspace(s[i]); i++) /* skip white space */
  20. ;
  21. sign = (s[i] == '-') ? -1 : 1;
  22. if (s[i] == '+' || s[i] == '-')
  23. i++;
  24. for (val = 0.0; isdigit(s[i]); i++)
  25. val = 10.0 * val + (s[i] - '0');
  26. if (s[i] == '.')
  27. i++;
  28. for (power = 1.0; isdigit(s[i]); i++) {
  29. val = 10.0 * val + (s[i] - '0');
  30. power *= 10;
  31. }
  32.  
  33. if (s[i] == 'e' || s[i] == 'E') {
  34. i++;
  35. expsgn = 1;
  36. if (s[i] == '-')
  37. expsgn = -1;
  38. if (s[i] == '-' || s[i] == '+')
  39. i++;
  40. }
  41. for (exp = 0.0; isdigit(s[i]); i++)
  42. exp = 10.0 * exp + (s[i] - '0');
  43.  
  44. expv = 1.0;
  45. while (exp--) {
  46. expv *= 10.0;
  47. }
  48.  
  49. if (expsgn == -1)
  50. expv = 1 / expv;
  51.  
  52. return (sign * val / power * expv);
  53. }
  54.  
  55.  
  56. int
  57. main(int argc, char **argv) {
  58. double d;
  59. d = atof("1.332E2");
  60. printf("d = %lf\n", d);
  61. return (0);
  62. }
Advertisement
Add Comment
Please, Sign In to add comment