Advertisement
MeehoweCK

Untitled

Jul 30th, 2019
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.29 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3.  
  4. using namespace std;
  5.  
  6. int stringtoint(string liczba)
  7. {
  8.     int wynik = 0, potega = 1;
  9.  
  10.     for(int i = (liczba.size() - 1); i >= 0; --i)
  11.     {
  12.         wynik += (static_cast<int>(liczba[i]) - 48) * potega;
  13.         potega *= 10;
  14.     }
  15.  
  16.     return wynik;
  17. }
  18.  
  19. double stringtodouble(string liczba)
  20. {
  21.     bool ujemna = false;
  22.     if(liczba[0] == '-')
  23.         ujemna = true;
  24.     unsigned separator;
  25.     for(unsigned i = 0; i < liczba.size(); ++i)
  26.         if(liczba[i] == '.')
  27.         {
  28.             separator = i;
  29.             break;
  30.         }
  31.     double potega;
  32.     if(separator == 0)
  33.         potega = 0.1;
  34.     else
  35.     {
  36.         potega = 1;
  37.         for(unsigned i = 1; i < separator; ++i)
  38.             potega *= 10;
  39.         if(ujemna)
  40.             potega /= 10;
  41.     }
  42.  
  43.     double wynik = 0;
  44.     for(unsigned i = 0; i < liczba.size(); ++i)
  45.     {
  46.         if(ujemna && i == 0)
  47.             continue;
  48.         if(i == separator)
  49.             continue;
  50.         wynik += (static_cast<int>(liczba[i]) - 48) * potega;
  51.         potega /= 10;
  52.     }
  53.     if(ujemna)
  54.         return -wynik;
  55.     return wynik;
  56. }
  57.  
  58. int main()
  59. {
  60.     string liczba = "8.2438";
  61.     double dliczba = stringtodouble(liczba);
  62.     cout << dliczba << endl;
  63.     return 0;
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement