写两个函数,分别求两个整数的最大公约数和最小公倍数,用主函数调用这两个函数,并输出结果。两个整数由键盘输入。
- 思路:先写一个主函数,通过主函数调用子函数来分别求出最大公倍数和最小公约数。
- 代码如下:
#include<stdio.h>
int mgys;
int mgbs;
void maxgys(int a,int b);
void maxgbs(int a,int b);
int main()
{
int a,b;
printf("输入两个整数:");
scanf("%d%d",&a,&b);
maxgys(a,b);
maxgbs(a,b);
printf("最大公约数=%d\n",mgys);
printf("最小公倍数=%d\n",mgbs);
return 0;
}
void maxgys(int a,int b){//求最大公约数
int r,t;
if(a<b){
t=a;
a=b;
b=t;
}
while((r=a%b)!=0){
a=b;
b=r;
}
mgys=b;
}
void maxgbs(int a,int b){//求最小公倍数
mgbs=a*b/mgys;
}
运行结果:
或者也可以这样:
#include<stdio.h>
int mgys;
int mgbs;
int maxgys(int a,int b);
int maxgbs(int a,int b);
int main()
{
int a,b;
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)
{
mgbs=a*b/mgys;
return mgbs;
//或者: return (a*b/mgys)
}
运行结果: