简体   繁体   English

如何从 function 返回负值?

[英]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.此时 Sub 将为-321 And -321 * -1 = 321 .-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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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