读书人

最大公约数和最小公倍数的错解决思路

发布时间: 2012-05-03 14:06:56 作者: rapoo

最大公约数和最小公倍数的错
class max_gys{
public int f(int a,int b) {
int min = a;
int max = b;
if (a > b) {
min = b;
max = a;
}
if (min == 0)
return max;
else
return f(min,max-min);
}
}

class min_gbs extends max_gys{
public int f(int a,int b){
int m=super.f(a,b);
return (a*b)/m;
}
}

public class f1{
public static void main(String args[]){
max_gys m=new max_gys();
min_gbs n=new min_gbs();
System.out.println("最大公约数"+m.f(4,6)+"最小公倍数"+n.f(4,6));
}
}


最小公倍数调用的时候出了错,求解

[解决办法]
你在这里int m=super.f(a,b);是调用父类的方法,但是你父类的方法里调用的递归方法,又调用到子类里面的方法,所以你的调用不对,你吧你父类的方法和子类的方法名字不一致应该就能得到正确的结果了
[解决办法]

Java code
package com;public class Test1{    public int gys(int a, int b) {        if(a <= 0 || b <= 0) {            throw new IllegalArgumentException();        }        if(a % b == 0) {            return b;        } else {            return gys(b, a % b);        }    }        public int gbs(int a, int b) {        if(a <= 0 || b <= 0) {            throw new IllegalArgumentException();        }        return (a * b) / gys(a, b);    }        public static void main(String args[]){        Test1 test = new Test1();        System.out.println("最大公约数" + test.gys(4,6) + "最小公倍数" + test.gbs(4,6));    }} 

读书人网 >Java面试

热点推荐