//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;
}
}
這裏是我的問題:我注意到,如果我沒有在遞歸函數調用中使用「return」關鍵字,程序返回的值不正確,但是如果我單步執行該函數,本地值正確更新。我知道函數(除非它們是void類型)必須返回一個值。也許這個規則也適用於遞歸函數調用?基本C++遞歸程序問題
有人請詳細說明/幫助我理解嗎?
請問您能正確格式化您的代碼嗎?只需將其標記並按下Ctrl + K即可。 – mmmmmmmm 2009-10-04 13:52:16
@Nick D:謝謝:-) – mmmmmmmm 2009-10-04 14:03:36