簡體   English   中英

如何從 function 返回負值?

[英]How to return negative value from function?

下面是反轉負數的正數的代碼片段。但它總是返回所有負數的正數。如果有人知道發生了什么,請告訴我。

代碼:

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;
}

出色地:

return (sub * -1);

此時 Sub 將為-321 -321 * -1 = 321

通常的方法是編寫處理非負數的代碼,並將負數轉換為正數:

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

// code to reverse the digits goes here

if (neg)
    x = -x;

或者,如果您喜歡遞歸函數:

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