基本C++递归程序问题

noo*_*lla 1 c++ recursion

//This program finds the GCD of two numbers using a recursive function call via the
//Euclidean algorithm

#include <iostream>
#include <cmath>
using namespace std;

int GCD (int A, int B);

int main()
{
    int A = 45, B = 55;

    cout << "The GCD is " << GCD(A,B) << endl;
    //test
    return 0;
}

int GCD (int A, int B)
{
    A = abs(A);
    B = abs(B);


    if (A > B)
    {
        A = A - B;
        return GCD (A, B); //Recursive function call - works fine
        //GCD (A, B);  -- This function call seems to return an incorrect value

    else if (A < B)
    { 
        B = B - A;
        return GCD (A, B);//Recursive function call
        //GCD (A, B); -- This function call seems to return an incorrect value
    }

    else if (A = B)
    {
        return A;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的问题:我注意到如果我在递归函数调用中不使用"return"关键字,程序将返回一个不正确的值,但如果我单步执行该函数,则本地值将正确更新.我知道函数(除非它们的类型为void)必须返回一个值.也许这个规则也适用于递归函数调用?

有人可以详细说明/帮助我理解吗?

Kon*_*lph 7

也许这个规则也适用于递归函数调用?

为什么要适用不同的规则?递归函数与普通函数完全一样.

顺便说一句,您的程序包含一个错误:

else if (A = B)
{
    return A;
}
Run Code Online (Sandbox Code Playgroud)

这不是一个比较,它是一个任务 - 而且测试是不必要的,因为所有其他条件(A < BA > B)已经过测试.