C语言编程题?

2025-01-01 02:39:42
推荐回答(2个)
回答1:

一 根据算法写gcd函数

int gcd(int m, int n)

{

long s;

if (n == 0)

s = m;

else

s = gcd(n, m % n);

return s;

}

二 main主函数调用gcd函数测试

int main() {

int n, m, t;

while (true)

{

printf("输入两个数,用空格分开:\n");

scanf("%d %d", &m, &n);

t = gcd(m, n);

printf("最大公约数:%d\n", t);

}

}

三 运行结果

回答2:

#include
int Gcd(int m,int n)
{
int op;
while(m != n){//当m不等于n时继续辗转相除
while(m > n){
m -= n;
}//直到m小于等于n (其实就是求余数)
op = m;//交
m = n; //换
n = op;//m和n
}
return m;//或者return n,因为m = n
}
int main() {

int m, n, op;
scanf("%d%d", &m , &n);
if(m < n){//当m小于n
op = m;//交
m = n; //换
n = op;//m和n
}
printf("%d", Gcd(m, n));
return 0;
}