用C++设计一个子函数,找出任意2个整数的最大公约数,并在主函数中输入数据调用函数,在主函数中输出结果。
时间: 2024-05-10 11:19:44 浏览: 12
下面是一个示例代码:
```c++
#include <iostream>
using namespace std;
// 定义函数,计算两个数的最大公约数
int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
int main() {
int num1, num2;
// 输入两个整数
cout << "请输入两个整数:" << endl;
cin >> num1 >> num2;
// 调用函数,计算最大公约数
int result = gcd(num1, num2);
// 输出结果
cout << num1 << "和" << num2 << "的最大公约数为:" << result << endl;
return 0;
}
```
在上面的代码中,我们定义了一个 `gcd` 函数,用于计算任意两个整数的最大公约数。在主函数中,我们首先输入两个整数,然后调用 `gcd` 函数计算它们的最大公约数,并将结果输出。
相关问题
编写函数求两个整数的最大公约数和最小公倍数。要求两个整数 以及结果在 主函数中输入输出。c++
以下是求两个整数的最大公约数和最小公倍数的C++代码:
```cpp
#include <iostream>
using namespace std;
int gcd(int a, int b) { // 求最大公约数
if (b == 0) return a;
return gcd(b, a % b);
}
int lcm(int a, int b) { // 求最小公倍数
return a / gcd(a, b) * b;
}
int main() {
int a, b;
cout << "请输入两个整数: ";
cin >> a >> b;
cout << "最大公约数为: " << gcd(a, b) << endl;
cout << "最小公倍数为: " << lcm(a, b) << endl;
return 0;
}
```
在以上代码中,我们定义了两个函数gcd和lcm,分别用来求最大公约数和最小公倍数。主函数中首先输入两个整数,然后调用这两个函数分别输出它们的最大公约数和最小公倍数。
写两个函数,分别求两个整数的最大公约数和最小公倍数用主函数调用两个函数并输出结果两个整数由键盘输入C++
以下是C++实现求两个整数的最大公约数和最小公倍数的代码,主函数调用两个函数并输出结果,两个整数由键盘输入:
```c++
#include <iostream>
using namespace std;
// 求最大公约数
int maxyue(int a, int b) {
int c, yue = 0;
for (c = 1; c <= a && c <= b; c++) {
if (a % c == 0 && b % c == 0) {
yue = c;
}
}
return yue;
}
// 求最小公倍数
int minbei(int a, int b) {
int yue = maxyue(a, b);
int bei = (a * b) / yue; // 最小公倍数=两个数相乘/最大公约数
return bei;
}
int main() {
int a, b;
cout << "请输入两个数:";
cin >> a >> b;
cout << "最大公约数为:" << maxyue(a, b) << endl;
cout << "最小公倍数为:" << minbei(a, b) << endl;
return 0;
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)