简体   繁体   中英

How to return negative value from function?

Below is the code snippet of reversing a positive of a negative number.But it always returning positive number of all negative numbers.If anyone know what's happening please do let me know.

code:

int reverse(int x){
    int sub=0;
    if(x<0){
        while (x!=0){
        sub = sub*10 + x%10;
        x = x/10;
        }
        return (sub * -1);
    }
    else{
        while (x!=0)
        {
            sub = sub*10 + x%10;
            x = x/10;
        }
        return sub;
    }
    
}

int main(){
    int x = -123;
    cout<<reverse(x);
    cout<<c;
    return 0;
}

Well:

return (sub * -1);

Sub will be -321 at this time. And -321 * -1 = 321 .

The usual approach is to write code that handles non-negative numbers, and convert negative numbers to positive:

bool neg = false;
if (x < 0) {
    neg = true;
    x = -x;
}

// code to reverse the digits goes here

if (neg)
    x = -x;

or, if you like recursive functions:

int reverse(int x) {
    if (x < 0)
        return -reverse(-x);

    // code to reverse the digits goes here

    return whatever;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM