簡體   English   中英

如果遞歸調用應該在 a 或 b 變為 0 時停止並返回,那么為什么這個最大公約數程序的輸出為 -1

[英]Why the output of this greatest common divisor program is coming as -1 if the recursive call should stop and return when a or b becomes 0

1.該方法采用兩個參數來計算最大公約數。 2.程序不返回a或b的值,而是返回-1。

public static int gcd(int a,int b)
    {

        if(a==0 && b>0)
        {
            // returns when a becomes  0
            return b;
        }
        else if(b==0 && a>0)
        {
            //returns when b becomes 0
            return a;

        }
        else if(a>b)
         gcd(b,a%b);
        else 
            gcd(a,b%a);

        return -1;
    }

您也需要返回遞歸調用。 所以不需要返回-1

public static int gcd(int a, int b) {

    if (a == 0 && b > 0) {
        // returns when a becomes  0
        return b;
    } else if (b == 0 && a > 0) {
        //returns when b becomes 0
        return a;

    } else if (a > b) {
        return gcd(b, a % b);
    } else {
        return gcd(a, b % a);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM