-3

I tried to inverse the number. Ex: 243 > 342 its my quiz from school (Not to be graded)

#include <iostream>

using namespace std;

int main()
{
    int n, reverse, rem;
    cout << "Enter a number: ";
    cin >> n;
    while (n != 0)
    {
        rem = n % 10;
        reverse = reverse / 10 + rem;
        n /= 10;
    }
    cout << "Reversed Number: " << reverse << endl;
    return 0;
} 
anastaciu
  • 23,467
  • 7
  • 28
  • 53
  • 2
    There are at least two bugs in the shown code. `reverse` is never initialized. And there seems to be some confusion between what multiplication and division does. Does it make sense to you that the shown code keeps dividing both `reverse` and `n`, by 10, each time through the loop? As Mr. Spock would say: this is not logical. – Sam Varshavchik Jun 15 '20 at 12:37
  • 2
    Always initialise your variables. – molbdnilo Jun 15 '20 at 12:37
  • You may want to treat the number as a string and then invert the characters in the string. – vinx.py Jun 15 '20 at 12:38
  • You correct it by thinking about what you're doing. Let's say `reverse` is 1, and `rem` is 2. Then `reverse/10+rem` is 2, but you want it to be 12. How do you make 12 from 1 and 2? – molbdnilo Jun 15 '20 at 12:41
  • Somewhat related: In the first iteration the line `reverse=reverse/10+rem` is reading the unintialized `reverse` variable and you therefore have undefined behavior. – Ted Lyngmo Jun 15 '20 at 12:47

2 Answers2

1

You should do reverse = reverse* 10 + rem; instead of division:

#include <iostream>

using namespace std;

int main()
{
    int n = 0, reverse = 0, rem = 0;
    cout << "Enter a number: ";
    cin >> n;
    while (n != 0)
    {
        rem = n % 10;
        reverse = reverse * 10 + rem;
        n /= 10;
    }
    cout << "Reversed Number: " << reverse << endl;
    return 0;
}
anastaciu
  • 23,467
  • 7
  • 28
  • 53
NixoN
  • 661
  • 1
  • 6
  • 19
0

you can try this

#include <iostream>  
using namespace std;  
int main()  
{  
int n, reverse=0, rem;    
cout<<"Enter a number: ";    
cin>>n;    
  while(n!=0)    
  {    
     rem=n%10;      
     reverse=reverse*10+rem;    
     n/=10;    
  }    
 cout<<"Reversed Number: "<<reverse<<endl;     
return 0;  
}