Guest User

Übung atof Leange

a guest
Apr 30th, 2016
409
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <iostream>
  3.  
  4. double _atof_(const char *x);
  5. double _pow_(int x, int y);
  6.  
  7. int main()
  8. {
  9.     printf("%lf\n", _atof_("3.141592"));
  10.     printf("%lf\n", _atof_("-3.14159"));
  11.     printf("%lf\n", _atof_("78"));
  12.     printf("%lf\n", _atof_("-78"));
  13.     printf("%lf\n", _atof_("3.14159_"));
  14.     printf("%lf\n", _atof_("3.141.59"));
  15.     printf("%lf\n", _atof_("-3."));
  16.     printf("%lf\n", _atof_("-"));
  17.     printf("%lf\n", _atof_("-b"));
  18.     printf("%lf\n", _atof_("ABCDEFG"));
  19.  
  20.     std::cin.get();
  21.     return 0;
  22. }
  23.  
  24. double _atof_(const char *x)
  25. {
  26.     double res = 0.0;
  27.     double res2 = 0.0;
  28.     bool neg = false;
  29.     int help = -1;
  30.     int dot = 0;
  31.  
  32.     if (x[0] == '-')
  33.     {
  34.         neg = true;
  35.     }
  36.        
  37.     for (int i = 0 + neg; x[i] != '\0'; i++)
  38.     {
  39.         int val = (x[i] - 48);
  40.  
  41.         if ((val < 0) || (val > 9))
  42.         {
  43.             if (val == -2 && i != 0 && dot == 0 && x[i+1] != '\0')
  44.             {
  45.                 dot = i;
  46.             }
  47.             else
  48.                 return 0.0;
  49.         }
  50.         else if (dot == 0)
  51.         {
  52.             res += val / _pow_(10, i);
  53.             help += 1;
  54.         }
  55.         else
  56.         {
  57.             res2 += val / _pow_(10, i-dot);
  58.         }              
  59.     }
  60.  
  61.     res *= _pow_(10, help + neg);
  62.     res += res2;
  63.  
  64.     if (neg == true)
  65.     {
  66.         res -= res * 2;
  67.     }
  68.     return res;
  69. }
  70.  
  71. double _pow_(int x, int y)
  72. {
  73.     if (y == 0)
  74.         return 1;
  75.     else if (y == 1)
  76.         return x;
  77.     else
  78.     {
  79.         int res = x;
  80.         for (int i = 1; i < y; i++)
  81.         {
  82.             res *= x;
  83.         }
  84.         return res;
  85.     }
  86.     return 0.0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment