Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   reversing input numbers (http://www.go4expert.com/forums/reversing-input-numbers-t28298/)

Valiantangel 29Apr2012 12:28

reversing input numbers
 
Hi came up with his code, basically to reverse whatever input you key in. However when i key in 0 or 0001 or -101 they donot reverse.What have i done wrong and how to correct?

Code:

#include <iostream>

using namespace std;

int main ()
{
  long int y = 0,x;
  cout <<"Enter any numeric value to be reversed:";
  cin>> x;
   
    while (x > 0)
    {
        y *= 10;
        y += x % 10;
        x /= 10;

    }
    cout <<y <<"\n";
   
    return(0);
}


Valiantangel 29Apr2012 12:37

Re: reversing input numbers
 
Mmmmmm it could be because i am using %modulus so if that is the case, should i re-frame from using modulus for negative numbers?How about 0s? any help?

Valiantangel 29Apr2012 13:11

Re: reversing input numbers
 
i think in all likelihood because of integer.

Anindya1989 30Apr2012 01:44

Re: reversing input numbers
 
Quote:

Originally Posted by Valiantangel (Post 94614)
Mmmmmm it could be because i am using %modulus so if that is the case, should i re-frame from using modulus for negative numbers?How about 0s? any help?

Yes its definitely because of the modulus. As it turns out Cís modulo operator behaves differently from the mathematically defined ones when we apply it for negative numbers.
The C90 standard does not define the result of modulus applied on negative numbers, so the result is compiler dependant.


All times are GMT +5.5. The time now is 17:28.