C - AtoF: Extend AtoF to handle scientific notation of the form 123.45e-6

r囧r小猫 2022-11-04 05:23 171阅读 0赞

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net

  1. /*
  2. * AtoF: Extend AtoF to handle scientific notation of the form 123.45e-6.
  3. *
  4. * AtoF_Scientific.c - by FreeMan
  5. */
  6. #include <stdio.h>
  7. #include <ctype.h>
  8. double AtoF(char s[]);
  9. int main(void)
  10. {
  11. printf("%f\n", AtoF("123.45e-6"));
  12. }
  13. double AtoF(char s[])
  14. {
  15. double val, power, base, p;
  16. int i, sign, exp;
  17. for (i = 0; isspace(s[i]); i++)
  18. ;
  19. sign = (s[i] == '-') ? -1 : 1;
  20. if (s[i] == '-' || s[i] == '+')
  21. {
  22. ++i;
  23. }
  24. for (val = 0.0; isdigit(s[i]); i++)
  25. {
  26. val = 10.0 * val + (s[i] - '0');
  27. }
  28. if (s[i] == '.')
  29. {
  30. i++;
  31. }
  32. for (power = 1.0; isdigit(s[i]); i++)
  33. {
  34. val = 10.0 * val + (s[i] - '0');
  35. power *= 10.0;
  36. }
  37. if (s[i] == 'e' || s[i] == 'E')
  38. {
  39. i++;
  40. }
  41. else
  42. {
  43. return sign * val / power;
  44. }
  45. base = (s[i] == '-') ? 0.1 : 10.0; /* 10^(-n) = 1/10^n = (1/10)^n = (0.1)^n */
  46. if (s[i] == '+' || s[i] == '-')
  47. {
  48. i++;
  49. }
  50. for (exp = 0; isdigit(s[i]); i++)
  51. {
  52. exp = 10 * exp + (s[i] - '0');
  53. }
  54. for (p = 1; exp > 0; --exp)
  55. {
  56. p = p * base;
  57. }
  58. return (sign * (val / power)) * p;
  59. }
  60. // Output:
  61. /*
  62. 123.450000
  63. */

发表评论

表情:
评论列表 (有 0 条评论,171人围观)

还没有评论,来说两句吧...

相关阅读