strtod.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <stdlib.h>
  2. #include <math.h>
  3. #include <stdio.h>
  4. double strtod(const char *nptr, char **endptr) {
  5. int sign = 1;
  6. if (*nptr == '-') {
  7. sign = -1;
  8. nptr++;
  9. }
  10. long long decimal_part = 0;
  11. while (*nptr && *nptr != '.') {
  12. if (*nptr < '0' || *nptr > '9') {
  13. break;
  14. }
  15. decimal_part *= 10LL;
  16. decimal_part += (long long)(*nptr - '0');
  17. nptr++;
  18. }
  19. double sub_part = 0;
  20. double multiplier = 0.1;
  21. if (*nptr == '.') {
  22. nptr++;
  23. while (*nptr) {
  24. if (*nptr < '0' || *nptr > '9') {
  25. break;
  26. }
  27. sub_part += multiplier * (*nptr - '0');
  28. multiplier *= 0.1;
  29. nptr++;
  30. }
  31. }
  32. double expn = (double)sign;
  33. if (*nptr == 'e' || *nptr == 'E') {
  34. nptr++;
  35. int exponent_sign = 1;
  36. if (*nptr == '+') {
  37. nptr++;
  38. } else if (*nptr == '-') {
  39. exponent_sign = -1;
  40. nptr++;
  41. }
  42. int exponent = 0;
  43. while (*nptr) {
  44. if (*nptr < '0' || *nptr > '9') {
  45. break;
  46. }
  47. exponent *= 10;
  48. exponent += (*nptr - '0');
  49. nptr++;
  50. }
  51. expn = pow(10.0,(double)(exponent * exponent_sign));
  52. }
  53. if (endptr) {
  54. *endptr = (char *)nptr;
  55. }
  56. double result = ((double)decimal_part + sub_part) * expn;
  57. return result;
  58. }