This code snippet is supposed to return the reverse of the given integer and in the Sololearn compiler it works but in VSCode and Code::Blocks the output is different.
For 543 it returns -93835951 in VSCode and 694653940 in Code::Blocks.
Does anybody know why?
#include <iostream>
using namespace std;
int main()
{
int n, sum, a;
a = 0;
sum = 0;
cin >> n;
while (n>0)
{
a = n % 10;
sum = sum * 10 + a;
n = n / 10;
}
cout << sum;
return 0;
}
Here is the working version with a bit of refactoring but still keeping it very similar to your snippet:
#include <iostream>
int main( )
{
std::cout << "Enter a number: ";
int num { };
std::cin >> num;
int sum { };
while ( num > 0 )
{
const int remainder { num % 10 };
sum = sum * 10 + remainder;
num = num / 10;
}
std::cout << "The reversed number: " << sum << '\n';
}
A few general things to keep in mind:
using namespace std;
. That's a bad practice. See Why is "using namespace std;" considered bad practice?.remainder
inside the scope of the while
loop because it was not being used outside the loop.int a
, int n
, etc. These are not meaningful and purposeful names in this context. Use names that MAKE sense.