1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

reversing input numbers

Discussion in 'C++' started by Valiantangel, Apr 29, 2012.

  1. Valiantangel

    Valiantangel New Member

    Joined:
    Apr 14, 2012
    Messages:
    6
    Likes Received:
    0
    Trophy Points:
    0
    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);
    }
     
  2. Valiantangel

    Valiantangel New Member

    Joined:
    Apr 14, 2012
    Messages:
    6
    Likes Received:
    0
    Trophy Points:
    0
    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?
     
  3. Valiantangel

    Valiantangel New Member

    Joined:
    Apr 14, 2012
    Messages:
    6
    Likes Received:
    0
    Trophy Points:
    0
    i think in all likelihood because of integer.
     
  4. Anindya1989

    Anindya1989 New Member

    Joined:
    Apr 29, 2012
    Messages:
    2
    Likes Received:
    0
    Trophy Points:
    0
    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.
     

Share This Page