1

In the following block of code I've passed in a random number which i want to break up into base 20 components. For example, the number 12280, It can be broken up into . 1 x 20^3 + 10 x 20^2 + 14 x 20^1.The for loop here will take that random number, subtract it by 20^(randomNumber), and then if it gives a negative number then it will proceed to the next lower exponent until it finds the one that gives a positive number. Then the while loop will take the random number, subtract it by 20^(exponent that the first for loop found) then shove it into the vector. Then it keeps doing down until we get to 0.

Here is my question When i try to run the program(for randNum=12280), the program outputs 1 of 3, 10 of 2s, and 13 of 1s, instead of 14 of 1s. It is always off by one. How can I make it so that it will give me 14 of 1s?

   vector<int> brokenUp(int randNum)
{

    vector<int> powers;
    double temp = randNum;

    for (int j = randNum; j > 0; j--)                                              
    {
        if (temp - pow(20, j) < 0)
        {
            continue;
        }
        while (temp - pow(20, j) > 0)
        {
            temp = temp - pow(20, j);
            powers.push_back(j);
        }
    }


    for (unsigned int e = 0; e < powers.size(); e++)
    {
        cout << powers.at(e) << endl;
    }
     return powers;
}
Blorglue
  • 15
  • 2
  • 1
    If you don't want to deal with mysterious rounding errors when using `double` values, then don't use `double` values. Reimplement your algorithm using strict integer math. That means that `pow()` is off-limits too. The rule of thumb is: any integer-related algorithm that somehow ends up using `pow()` is broken by design. You can trivially implement this base 20 calculation using nothing more than division and remainder-based math. – Sam Varshavchik Nov 10 '20 at 00:50
  • 1
    @SamVarshavchik While this is true, it's not the problem here. (or rather, it's not the reason the result is wrong...) – JasonD Nov 10 '20 at 01:04
  • @JasonD I've fixed it by implementing the ceil functions to deal with the rounding errors. – Blorglue Nov 24 '20 at 05:24

0 Answers0