c语言写出两个函数,分别用于求两个整数的最大公约数和最小公倍数,用主函数调用这两个函数,并输出结果,两个整数由键盘输入。
时间: 2023-11-27 07:09:22 浏览: 29
下面是两个函数的实现:
```c
int gcd(int a, int b) {
int temp;
while(b != 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
int lcm(int a, int b) {
int gcd_value = gcd(a, b);
return (a / gcd_value) * b;
}
```
其中,`gcd` 函数使用辗转相除法求最大公约数,`lcm` 函数则利用最大公约数求最小公倍数。
下面是主函数的实现:
```c
#include <stdio.h>
int main() {
int a, b;
printf("请输入两个整数:");
scanf("%d %d", &a, &b);
int gcd_value = gcd(a, b);
int lcm_value = lcm(a, b);
printf("%d 和 %d 的最大公约数为:%d\n", a, b, gcd_value);
printf("%d 和 %d 的最小公倍数为:%d\n", a, b, lcm_value);
return 0;
}
```
主函数中,先读入两个整数,然后调用 `gcd` 和 `lcm` 函数分别求出最大公约数和最小公倍数,并输出结果。
相关问题
c语言写出两个数 分别求出两个整数的最大公约数和最小公倍数 用主函数调用这两个函数
好的,下面是代码实现:
```
#include <stdio.h>
int gcd(int a, int b); // 求最大公约数的函数声明
int lcm(int a, int b); // 求最小公倍数的函数声明
int main() {
int num1, num2;
printf("请输入两个正整数:\n");
scanf("%d %d", &num1, &num2);
printf("%d和%d的最大公约数为:%d\n", num1, num2, gcd(num1, num2));
printf("%d和%d的最小公倍数为:%d\n", num1, num2, lcm(num1, num2));
return 0;
}
int gcd(int a, int b) {
int temp;
while (b != 0) {
temp = b;
b = a % b;
a = temp;
}
return a;
}
int lcm(int a, int b) {
return a * b / gcd(a, b);
}
```
上述代码中,`gcd`函数用来求最大公约数,使用辗转相除法进行计算;`lcm`函数用来求最小公倍数,直接利用公式`最小公倍数=两数之积÷最大公约数`进行计算。主函数中先输入两个正整数,然后分别调用`gcd`和`lcm`函数进行计算并输出结果。
写出两个函数分别求出两个整数的最大公约数和最小公倍数,用主函数调用这两个函数
以下是C语言实现求两个整数的最大公约数和最小公倍数的代码,其中maxgys()函数用于求最大公约数,maxgbs()函数用于求最小公倍数,main()函数用于调用这两个函数并输出结果:
```c
#include <stdio.h>
int maxgys(int a, int b);
int maxgbs(int a, int b);
int main() {
int a, b, mgys, mgbs;
printf("请输入两个数:");
scanf("%d%d", &a, &b);
mgys = maxgys(a, b);
mgbs = maxgbs(a, b);
printf("最大公约数=%d\n", mgys);
printf("最小公倍数=%d\n", mgbs);
return 0;
}
int maxgys(int a, int b) {
int t, r;
if (a < b) {
t = a;
a = b;
b = t;
}
while ((r = a % b) != 0) {
a = b;
b = r;
}
return b;
}
int maxgbs(int a, int b) {
int mgys = maxgys(a, b);
return a * b / mgys;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)