1

I have to write a program which converts octal fractions to decimal. I wrote code which works in some situations, however it doesn't work with smaller numbers, I don't know why.

Here's my code:

int testy,p=0,wykladnik;
    string tmpLiczba;
    string liczba = "";
    long double wynik=0,liczba_dec,wynik_osiem;
    cout << "Podaj liczbe testow:" << endl;
    cin >> testy;
    string *wyniki = new string[testy]; //for later
    for (int i = 0; i < testy; i++)
    {
        cin >> liczba;
        liczba.erase(0, 2);

        for (int j = 0; j < liczba.length();j++)
        {
            tmpLiczba = liczba[j];

            liczba_dec = stoi(tmpLiczba);

            wykladnik = -(j + 1);

            wynik_osiem = pow(8, wykladnik);

            wynik += liczba_dec*wynik_osiem;

        }

        cout << wynik << endl;
        wynik = 0;

    }

(Im getting only number lower than 1, so I can remove to first digits, because they didn't count at all.) So here's my input and output:

input--> 0.75

output-->0.953125

input-->0.0001

output-->0.000244141

input-->0.01234567

output-->0.0204081

And these are correct values that i should recive with this input:

0.953125

0.000244140625

0.020408093929290771484375

Milk
  • 25
  • 3
  • `cout` cuts floats to certain precision. Try changing that. – hyde Jan 14 '18 at 12:48
  • i hope this helps you http://en.cppreference.com/w/cpp/io/manip/setprecision – Albin Paul Jan 14 '18 at 12:52
  • 2
    When adding several floating point numbers, you should consider that there can a small error in each conversion, and that the errors also add up. For an example, see [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Bo Persson Jan 14 '18 at 12:52

1 Answers1

1
#include <iomanip>
cout << std::setprecision(25) <<wynik << endl;

for long double, you should test the size, cause some compiler uses double as long double, which can not hold that many effective digits.

phy nju
  • 289
  • 2
  • 7