4.2.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /* Exercise 4-2. Extend atof to handle scientific notation of the form
  2. 123.45e-6
  3. where a floating-point number may be followed by e or E and an optionally signed exponent.
  4. */
  5. #include <ctype.h>
  6. #include <stdio.h>
  7. /* atof: convert string s to double */
  8. double atof(char s[]);
  9. int main()
  10. {
  11. double d = atof("3.5e111");
  12. printf("%e \n",d);
  13. }
  14. double atof(char s[])
  15. {
  16. double val, power, exp;
  17. int i, sign, expsign, expval;
  18. for (i = 0; isspace(s[i]); i++) /* skip white space */
  19. ;
  20. sign = (s[i] == '-') ? -1 : 1;
  21. if (s[i] == '+' || s[i] == '-')
  22. i++;
  23. for (val = 0.0; isdigit(s[i]); i++)
  24. val = 10.0 * val + (s[i] - '0');
  25. if (s[i] == '.')
  26. i++;
  27. for (power = 1.0; isdigit(s[i]); i++) {
  28. val = 10.0 * val + (s[i] - '0');
  29. power *= 10;
  30. }
  31. if ((s[i] == 'e') || (s[i] == 'E'))
  32. {
  33. i++;
  34. if (s[i]=='-')
  35. {
  36. expsign = 0.0;
  37. i++;
  38. }
  39. else expsign=1.0;
  40. exp = 1;
  41. if (isdigit(s[i]))
  42. for (expval = 0.0; isdigit(s[i]); i++)
  43. expval = 10.0 * expval + (s[i] - '0');
  44. for (int j=0; j<expval; j++)
  45. {
  46. if (expsign) exp *= 10.0;
  47. else exp /= 10.0;
  48. }
  49. }
  50. return ((sign * val) / power) * exp;
  51. }