求两个正整数的最大公约数。编写求最大公约数的函数Gcd(),主函数中输入任意两个整数,调用此函数求最大公约数并输出结果。 要求函数原型为:int Gcd(int a, int b),a、b为输入的任意两个整数,当a或b为0或负数时,函数返回值为-1,否则返回a、b的最大公约数。 示例: Input a,b:4,48 Greatest Common Divisor of 4 and 48 is 4 输入提示"Input a,b:" 输入格式"%d,%d" 输出提示及格式:"Greatest Common Divisor of %d and %d is %d\n" or "Input number should be positive!\n"
时间: 2024-02-15 09:05:09 浏览: 37
好的,下面是符合要求的代码实现:
```c++
#include <iostream>
using namespace std;
int Gcd(int a, int b) {
if (a <= 0 || b <= 0) { // a或b为0或负数时返回-1表示出错
return -1;
}
while (a % b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return b;
}
int main() {
int a, b;
cout << "Input a,b:";
scanf("%d,%d", &a, &b);
int gcd = Gcd(a, b);
if (gcd == -1) {
cout << "Input number should be positive!\n";
} else {
printf("Greatest Common Divisor of %d and %d is %d\n", a, b, gcd);
}
return 0;
}
```
函数Gcd()的实现与之前的相同。在主函数中,首先输入两个整数,然后调用Gcd()函数求最大公约数,最后判断是否出错并输出结果。
注意,当a或b为0或负数时,函数Gcd()返回-1表示出错。在输出结果时,使用了printf()函数并按照要求格式化输出。
相关问题
编写函数求两个正整数的最大公约数,并在main主函数中调用该函数求输入的两个整数的最大公约数和最小公倍数。
以下是一个求两个正整数最大公约数和最小公倍数的函数及其在main函数中的调用示例:
```c++
#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 * b / gcd(a, b);
}
int main() {
int a, b;
cout << "请输入两个正整数:";
cin >> a >> b;
cout << "它们的最大公约数是:" << gcd(a, b) << endl;
cout << "它们的最小公倍数是:" << lcm(a, b) << endl;
return 0;
}
```
运行结果:
```
请输入两个正整数:12 18
它们的最大公约数是:6
它们的最小公倍数是:36
```
用c语言编写函数求出任意两个正整数的最大公约数和最小公倍数。在主函数中输入这两个数
好的,以下是C语言的函数代码:
```c
#include <stdio.h>
int gcd(int a, int b) { // 求最大公约数
return b == 0 ? a : gcd(b, a % b);
}
int lcm(int a, int b) { // 求最小公倍数
return a * b / gcd(a, b);
}
int main() {
int a, b;
printf("请输入两个正整数:");
scanf("%d %d", &a, &b);
printf("它们的最大公约数为:%d\n", gcd(a, b));
printf("它们的最小公倍数为:%d\n", lcm(a, b));
return 0;
}
```
使用时,可以直接调用 `gcd` 函数和 `lcm` 函数分别求解最大公约数和最小公倍数。在 `main` 函数中,使用 `scanf` 函数输入两个整数,然后输出结果即可。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)