c++程序设计,分别用函数和不用函数写用辗转相除法求最大公约数
时间: 2024-03-23 11:40:33 浏览: 66
不用函数的方法:
```cpp
#include<iostream>
using namespace std;
int main()
{
int a, b;
cout<<"Enter two numbers: ";
cin>>a>>b;
int r;
while(b!=0)
{
r = a % b;
a = b;
b = r;
}
cout<<"The GCD of the two numbers is "<<a<<endl;
return 0;
}
```
使用函数的方法:
```cpp
#include<iostream>
using namespace std;
int gcd(int a, int b)
{
int r;
while(b!=0)
{
r = a % b;
a = b;
b = r;
}
return a;
}
int main()
{
int x, y;
cout<<"Enter two numbers: ";
cin>>x>>y;
int result = gcd(x, y);
cout<<"The GCD of the two numbers is "<<result<<endl;
return 0;
}
```
注意,使用函数的方法需要在程序中定义一个函数 `gcd`,该函数接收两个整数作为参数,使用辗转相除法求解最大公约数,并返回结果。在 `main` 函数中,先输入两个整数,再调用 `gcd` 函数求解最大公约数,并输出结果。
阅读全文
相关推荐

















