Advertisement
levartolona

C_PRG_LANG_EX_4.2

Feb 1st, 2020
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.01 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <limits.h>
  5. #include <ctype.h>
  6.  
  7. double my_atof(char *str)
  8. {
  9.     double res = 0;
  10.  
  11.     while(!isdigit(*str) && *str != 'e' && *str != 'E' && *str != '-')
  12.         str++;
  13.  
  14.     if (*str == 'e' || *str == 'E')
  15.         return 0;
  16.  
  17.     int sign_numb = 1;
  18.     if (*str == '-')
  19.     {
  20.         sign_numb = -1;
  21.         str++;
  22.     }
  23.  
  24.     if (*str == 'e' || *str == 'E')
  25.         return 0;
  26.  
  27.     while (isdigit(*str))
  28.         res = res * 10 + (*str++ - '0');
  29.  
  30.     if (!*str)
  31.         return res * sign_numb;
  32.  
  33.     int power = 0;
  34.     if (*str == '.')
  35.     {
  36.         str++;
  37.         while (isdigit(*str))
  38.         {
  39.             res = res * 10 + (*str++ - '0');
  40.             power++;
  41.         }
  42.         for (int i = 0; i < power; i++)
  43.         res /= 10;
  44.     }
  45.  
  46.     if (!*str)
  47.         return res * sign_numb;
  48.  
  49.     int exp = 0;
  50.     if (*str == 'e' || *str == 'E')
  51.     {
  52.         str++;
  53.         int sign_exp = 0;
  54.         if (*str == '-')
  55.         {
  56.             sign_exp++;
  57.             str++;
  58.         }
  59.  
  60.         while (isdigit(*str))
  61.             exp = exp * 10 + (*str++ - '0');
  62.  
  63.         if (sign_exp)
  64.             for (int i = 0; i < exp; i++)
  65.                 res /= 10;
  66.         else
  67.             for (int i = 0; i < exp; i++)
  68.                 res *= 10;
  69.  
  70.     }
  71.  
  72.     return res * sign_numb;
  73. }
  74.  
  75. int main(void)
  76. {
  77.     double res = 0;
  78.     res = my_atof("123");
  79.     printf("%s %lf\n", "123", res);
  80.  
  81.     res = my_atof("123.456");
  82.     printf("%s %lf\n", "123.456", res);
  83.  
  84.     res = my_atof("-123");
  85.     printf("%s %lf\n", "-123", res);
  86.  
  87.     res = my_atof("-123.456");
  88.     printf("%s %lf\n", "-123.456", res);
  89.  
  90.     res = my_atof("123.456E4");
  91.     printf("%s %lf\n", "123.456E4", res);
  92.  
  93.     res = my_atof("123.456E-4");
  94.     printf("%s %lf\n", "123.456E-4", res);
  95.  
  96.     res = my_atof("-123.456E4");
  97.     printf("%s %lf\n", "-123.456E4", res);
  98.  
  99.     res = my_atof("-123.456E-4");
  100.     printf("%s %.8lf\n", "-123.456E-4", res);
  101.  
  102.     return 0;
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement