我不理解递归方法。

huangapple go评论78阅读模式
英文:

I do not understand recrusive methods

问题


    public static double calculatePower(double x, int y) {
        if (y == 0) 
           return 1;
        else 
           return (int) calculatePower(x, y-1);

我理解递归函数是如何被调用的,但是不理解它是如何被终止的。

我认为,如果在某一点上 y=1,由于 if 语句,函数应该返回 1
但实际上它没有这样做,我不明白为什么。

英文:

    public static double calculatePower (double x, int y) {
        if (y == 0) 
           return 1;
        else 
           return (int) calculatePower(x, y-1);

I understand how the recrusive function is called, but not how it is cancelled.

I think, if at some point y=1 the function should return 1 because of the if statement.
But it does not and I do not understand why

答案1

得分: 5

对于每次递归调用,传入的 y 参数都会减少一,因为你写了 calculatePower(x, y-1);。在某一点上,y 会变成 0,递归就会停止。

请注意,你的乘幂计算是错误的,你应该在实际的递归调用前添加 x * x * calculatePower(x, y-1)

英文:

For every recursive invocation the incoming y parameter is reduced by one since you write calculatePower(x, y-1);. At some point y is 0 and the recursion stops.

Note that your power calculation is wrong , you should add a x * before the actual recursive call: x * calculatePower(x, y-1)

答案2

得分: 3

这将在每次执行时从 y 减去 1。

我建议您在纸上手动执行它,以查看程序的工作原理。

例如:calculatepower(2,3) -> calculatepower(2,2) -> calculatepower(2,1) -> calculatepower(2,0)。现在,由于 y = 0,if 语句将被执行,它将返回 1。

然而,您的函数只会返回值 1(如果 y 是正数的话)。

这个 YouTube 教程会为您清晰地解释递归:
https://www.youtube.com/watch?v=neuDuf_i8Sg

英文:

This will subtract 1 from y every time it gets executed.

I recommend you execute it manually on paper to see how the program works.

ex: calculatepower(2,3) -> calculatepower(2,2) -> calculatepower(2,1) -> calculatepower(2,0). Now since y = 0 the if statement will get executed and it will return 1

Your function will only return the value 1 though (if y was a positive number)

This youtube tutorial will give you a clear explanation for recursion:
https://www.youtube.com/watch?v=neuDuf_i8Sg

huangapple
  • 本文由 发表于 2020年9月22日 19:40:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64008984.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定