0

Below code returns 7523503 instead of 7523505 in VS studio code. I ran it in an online IDE and it returns 7523505 as it's supposed to do. I've got g++ version 9.2.0 installed. How can I fix this?

#include <iostream>
#include <cmath>
using namespace std;
void inserare(int &n)
{
    int c = 0;
    int sol = 0;
    int uc1 = n%10;
    while(n!=0)
    {
        n /= 10; int uc2= n%10;
        if(uc2 != 0 && n % 10000 != 0)
        {
            sol += uc1 * pow(10,c++);
            int dif = uc1 - uc2;
            if(dif<0) dif *= -1;
            sol += dif * pow(10, c++);
        }
        else sol += uc1 * pow(10, c++);
        uc1 = uc2;
    }
    n = sol;
}
int main()
{
    int n = 7255;
    inserare(n);
    cout << n;
    return 0;
}
  • 3
    Please note that `std::pow` is a *floating point* function, and floating point operations have a tendency to result in compounding rounding errors. For powers of plain integers I recommend you create your own function to handle it using integer arithmetic. – Some programmer dude Oct 14 '22 at 11:30
  • 1
    I also recommend you use a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to step through your code line by line while monitoring variables and their values. That should help you figure out when and where things start to go wrong. And to be even clearer, break up expressions into smaller parts and save in temporary variables, so you can easily see results of intermediate operations. For example `sol += uc1 * pow(10,c++);` could be `auto t1 = pow(10, c++); auto t2 = uc1 * t1; sol += t2;` – Some programmer dude Oct 14 '22 at 11:33

0 Answers0