求帮看递归代码,实在改不对了
是我的static错了吗
题目:【题目描述】
从键盘任意输入两个正整数,求这两个数的最大公约数。要求使用递归的方法完成。
【输入样例】
24 36
【输出样例】
12
#include<stdio.h>
//使用递归方法完成求最大公约数
unsigned GetGreatestCommonDivisor(unsigned int x,unsigned int y);
int main()
{
unsigned int x,y,z;
scanf("%u %u",&x,&y);//输入语句
z=GetGreatestCommonDivisor(x,y);
printf("%u",z);//输出语句
return(0);
}
unsigned GetGreatestCommonDivisor(unsigned int x,unsigned int y)
{
static int i;
i=(x>y?y:x);
if(y!=x)
{
if(y%i==0&&x%i==0)
{
return (i);
}
else
{
i--;
return GetGreatestCommonDivisor(x,y);
}
}
else
return x;
}
修改如下,供参考:
#include<stdio.h>
//使用递归方法完成求最大公约数
unsigned GetGreatestCommonDivisor(unsigned int x,unsigned int y);
int main()
{
unsigned int x,y,z;
scanf("%u %u",&x,&y);//输入语句
z=GetGreatestCommonDivisor(x,y);
printf("%u",z);//输出语句
return(0);
}
unsigned GetGreatestCommonDivisor(unsigned int x,unsigned int y)
{
int i;
if (y > x){
i = y;
y = x;
x = i;
}
if (x % y == 0)
return y;
else
return GetGreatestCommonDivisor(y,x%y);
//i=(x>y?y:x);
//if(y!=x)
//{
//if(y%i==0&&x%i==0)
//{
// return (i);
//}
//else
//{
//i--;
//return
//GetGreatestCommonDivisor(x,y);
//}
//}
//else
// return x;
}
#include<stdio.h>
void g(int &x,int &y){
if(y==0)
return;
int a;
a=x%y;
x=y;
y=a;
g(x,y);
}
int main(){
int x,y;
int a,b;
scanf("%d%d",&x,&y);
if(x>y) g(x,y);
else if(x<y) g(y,x);
printf("%d",x);
}
或者这样更好一点。
#include<stdio.h>
int g(int x,int y){
if(y==0)
return x;
g(y,x%y);
}
int main(){
int x,y;
int a,b;
scanf("%d%d",&x,&y);
if(x>y) x=g(x,y);
else if(x<y) x=g(y,x);
printf("%d",x);
}