0

我创建了这个代码来获取y除以的整数值xy总是大于x

如何将其转换为递归?

class Main {

    public static void main(String[] args) {
        System.out.println(fact(3,6));
    }

    static int fact(int x, int y) {
        int counter=0, answer=y;

        while(!(answer==1 || answer<=0)) {
            counter++;
            answer = answer-x;
        }

        return counter;
    }
}
4

4 回答 4

3
int fact(int x, int y) {
    if (y < x)
        return 0;

    return 1 + fact(x, y-x);
}

或者,如果您更喜欢单行:

int fact(int x, int y) {
    return (y < x ? 0 : 1 + fact(x, y-x));
}

也就是说,如果是家庭作业(我希望是这样),您只需让最大的在线开发人员社区为您完成作业,在这种情况下,您无需付出太多努力就能获得好成绩。

如果不是,您应该问自己“这有什么用,我怎样才能做得更好?”。看来您只需要将一个整数除以另一个整数,所以没有什么比我投反对票的答案更简单的了;)。如果要获得除法的余数,可以使用模数 ( %) 运算符。如果您想四舍五入,您应该了解您的 API 并检查Math.round()/ceil()/floor(),或者通过检查其余部分自己做(为了好玩)(请参阅对我被否决的答案的评论)。

这里的许多开发人员会问您(并且已经这样做了):“您要实现什么目标?” 他们是对的。如果您想提高您的编程技能,请牢记大局并且不失去编写这个和那个方法的目的,始终是我们需要做的。

继续编程!:)

于 2013-10-01T14:07:51.960 回答
2

通常,while 循环中的条件将成为您的基本情况。通常您还需要跟踪您的计数器/答案作为参数

就像是:

class Main { 
    public static void main(String[] args){
        System.out.println(fact(3,6,0));
    }
    static int fact(int x, int y, int counter){
        if(!(y==1 || y<=0)) return counter;
        counter++;
        y= y-x;
        return fact(x,y,counter);
    }
}
于 2013-10-01T14:03:01.860 回答
0

试试这个:

static int fact(int x, int y){
       if (y - x > 1) {
           return fact(x, y-x)+1;
        return 0;
    }
于 2013-10-01T14:03:07.603 回答
-1

不需要递归;)

return y / x;

于 2013-10-01T14:00:08.833 回答