use*_*141 6 c++ function greatest-common-divisor
我已经启动了这个程序来计算最大的公约数.这是我到目前为止:
#include <iostream>
#include <math.h>
using namespace std;
int getGCD(int a, int b)
{
a = a % b;
if (a == 0)
{
return b;
b = b % a;
}
if (b == 0)
{
return a;
}
}
int main()
{
int x, y;
cout << "Please enter two integers x and y, for GCD calculation" << endl;
cin >> x >> y;
cout << "The GCD of " << x << "and " << y << " is" << getGCD(x, y) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我总是得到一个0的GCD.我究竟做错了什么?
您应该循环查找这一点,如果您使用一些方程来说明其如何工作的算法,这可能会有所帮助。
但是我看到你有两个问题,除非你在另一个循环内调用它。
在两种情况下(无论是 if 还是 else)都会返回,因此您只经过这里一次。
另外,这部分没有意义,为什么b在执行 a 后修改值return?
return b;
b = b%a;
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您应该为此使用递归。
http://rosettacode.org/wiki/Greatest_common_divisor#Recursive_Euclid_algorithm