标题:用递归求最大公因子
只看楼主
恰擊
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2011-11-8
结帖率:33.33%
已结贴  问题点数:20 回复次数:4 
用递归求最大公因子
不知道甚么原因,用RETURN把函数值传给MAIN函式时,会出现乱码的情况
#include <stdio.h>
#include <stdlib.h>
int gcd(int x,int y){
    if(x>y&&x!=0&&y!=0){
        gcd(x-y,y-y);
        }
    else if(x<y&&x!=0&&y!=0){
        gcd(x-x,y-x);
        }   
    else if(x==0){
        return y;
        }
    else if(y==0){
        return x;
        }
    }
int main(){
    int integer1,integer2,sum;
    printf("enter the two integers: ");
    scanf("%d %d",&integer1,&integer2);
    printf("gcd(%2d,%2d) = %d",integer1,integer2,gcd(integer1,integer2));<---问题所在
    system("pause");
    }
搜索更多相关主题的帖子: return include color 
2011-11-12 13:12
lwei
Rank: 5Rank: 5
等 级:职业侠客
威 望:3
帖 子:197
专家分:369
注 册:2005-5-4
得分:7 
感觉是计算符号优先级的问题,试试加上括号
if((x>y)&&(x!=0)&&(y!=0)){
        gcd(x-y,y-y);
        }
    else if((x<y)&&(x!=0)&&(y!=0)){

2011-11-12 15:04
心灵百合
Rank: 5Rank: 5
等 级:职业侠客
帖 子:215
专家分:367
注 册:2011-3-30
得分:7 
#include <stdio.h>
#include <stdlib.h>
int gcd(int x,int y){
    if(x>y&&x!=0&&y!=0){
        gcd(x-y,y-y);
        }
    else if(x<y&&x!=0&&y!=0){
        gcd(x-x,y-x);
        }   
    else if(x==0){
        return y;
        }
    else
        return x;
}
int main(){
    int integer1,integer2;
    printf("enter the two integers: ");
    scanf("%d %d",&integer1,&integer2);
    printf("gcd(%2d,%2d) = %d\n",integer1,integer2,gcd(integer1,integer2));
    system("pause");
    }
2011-11-12 21:31
恰擊
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2011-11-8
得分:0 
回复 2楼 lwei
#include <stdio.h>
#include <stdlib.h>
int gcd(int x,int y){
    if((x>y)&&(x!=0)&&(y!=0)){
        gcd(x-y,y-y);
        }
    else if((x<y)&&(x!=0)&&(y!=0)){
        gcd(x-x,y-x);
        }   
    else if(y==0){
        return x;
        }
    else if(x==0){
        return y;
        }
    }
int main(){
    int integer1,integer2;
    printf("enter the two integers: ");
    scanf("%d %d",&integer1,&integer2);
    printf("gcd(%2d,%2d) = %d",integer1,integer2,gcd(integer1,integer2));
    system("pause");
    }
加上括号后,结果也是乱码....请问大大们还有甚么可能性?
2011-11-13 10:43
dhyco
Rank: 2
等 级:论坛游民
帖 子:9
专家分:32
注 册:2011-3-29
得分:7 
#include <stdio.h>
#include <stdlib.h>
int gcd(int a,int b)
{
    int i;
    if(a>b)
    {
        i=a;
        a=b;
        b=i;
    }
    if(b%a!=0)
        gcd(a,b%a);
    else return a;
}
void main()
{
    int integer1,integer2;
    printf("enter the two integers: \n");
    scanf("%d %d",&integer1,&integer2);
    printf("gcd(%2d,%2d) = %d\n",integer1,integer2,gcd(integer1,integer2));
    system("pause");
}
2011-11-13 16:20



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-355067-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.330567 second(s), 8 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved