Search code examples
c++data-conversionfractions

Converting octal fractions to decimal - c++


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


Solution

  • #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.