注册 登录
编程论坛 C++教室

帮忙修改一个程序

sadsatan 发布于 2008-04-13 10:58, 638 次点击
//输入两个正整数m和n,求其最大公约数
using std::cout;
using std::cin;
using std::endl;
int main()
{
    int a,b,x,y;
    cout<<endl;
    cin>>a>>b;
    if(a>b)
    {
        x=a;
        y=b;
    }
    else
    {
        x=b;
        y=a;
    }
    if(x%y!=0)
    {
        while(x%y!=0)
        {
            x=x%y;
            y=y%x;
        }
    

        if(x=0)
            cout<<y;
        if(y=0)
            cout<<x;
    }
    else
        cout<<y;
    
    return 0;
}
6 回复
#2
sadsatan2008-04-13 11:00
我知道错的很厉害,但不知道错到哪了,请大家指点下
#3
江湖贫侠2008-04-13 11:36
在原程序基础上改了一下
int main()
{
    int a,b,x,y;
    cout<<"Input the two num except 0"<<endl;
    cin>>a>>b;
    if(a>b)
    {
        x=a;
        y=b;
    }
    else
    {
        x=b;
        y=a;
    }

    if(y==0 && x==0)
        cout<<"error input"<<endl;

    if (x%y==0)
    cout<<y<<endl;

    if(y!=0 && x%y!=0)
    {
        while(y!=0 && x%y!=0  )
        {
            x=x%y;
            y=y%x;
        }
        
        if(x==0)
            cout<<y<<endl;
        if(y==0)
            cout<<x<<endl;
        else
            cout<<y<<endl;
    
    }
   
    return 0;
}
#4
江湖贫侠2008-04-13 11:37
不好意思 没看到正整数的条件 把零也考虑在内了
#5
sadsatan2008-04-13 12:40
嗯,知道自己怎么错的了,谢谢啦
#6
sadsatan2008-04-13 13:03
但是还有问题:#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
    int a,b,x,y;
    cout<<endl;
    cin>>a>>b;
    if(a>b)
    {
        x=a;
        y=b;
    }
    else
    {
        x=b;
        y=a;
    }
    if(x%y!=0)
    {
        while(x%y!=0)
        {
            x=x%y;
            y=y%x;
        }
        if(x==0)
            cout<<y;
        if(y==0)
            cout<<x;
    }
    else
        cout<<y;
    return 0;
}
感觉程序也没错吧,
但是当我输入64和14的时候,
电脑就会出现异常
说应用程序出错……
#7
kaithwin2008-04-18 16:34
这是C++ prime 上面的用递归的算法
int rgcd(int v1,int v2)
{
    if(v2!=0)
        return rgcd(v2,v1%v2);
    return v1;
}
1