递归-一条语句中有两个调用 [英] Recursion - Two calls in one statement

查看:55
本文介绍了递归-一条语句中有两个调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试理解下面的代码片段中的递归调用.

I am trying to understand the recursion call in the below code snippet.

static long fib(int n) {
    return n <= 1 ? n : fib(n-1) + fib(n-2);
}

首先调用哪个函数调用?调用后方程如何工作?

Which function call does get called first? How does the equation work after the calls?

这两个函数都调用一次,然后应用方程式吗?或者先调用第一个,然后调用第二个?

Do both of these get called once and then equation applied or first one called and then the 2nd one?

也许是一个非常简单的问题!

Maybe a very simple question!

推荐答案

Java和C♯

子表达式按从左到右的顺序求值.在fib(n-2)之前评估fib(n-1).请参见 Java中评估顺序的规则是什么?

Java and C♯

Sub-expressions are evaluated in left-to-right order. fib(n-1) is evaluated before fib(n-2). See What are the rules for evaluation order in Java?

请务必注意,此处的评估顺序无关紧要,因为fib()没有任何副作用.

It's important to note that the order of evaluation doesn't matter here since fib() does not have any side effects.

以不确定的顺序调用这两个函数,并且一旦调用了它们,它们的返回值将加在一起并返回.您可能不知道,左边的函数可能先被调用,或者右边的函数先被调用.

The two functions are called in an indeterminate order, and once both have been called their return values are added together and returned. The left function could be called first, or the right one first, you don't know.

这看似有问题,但这不是问题,因为调用它们的顺序无关紧要.调用fib(i)没有任何副作用(例如,修改其他变量,打印消息等),因此这两个函数调用是完全独立的.

That may seem problematic, but it's not, because the order they're called doesn't matter. Calling fib(i) does not have any side effects (e.g. modifying other variables, printing a message, etc.), so the two function calls are entirely independent.

一个编译器可能会决定先评估左侧,再评估右侧:

One compiler might decide to evaluate the left side before the right:

 1. f(3)
 2.   f(2)
 3.     f(1)
 4.       return 1
 5.     f(0)
 6.       return 0
 7.     return 1 + 0
 8.   f(1)
 9.     return 1
10.  return 1 + 1

另一人可能会决定先评估右侧,再评估左侧:

Another one might decide to evaluate the right side before the left:

 1. f(3)
 2.   f(1)
 3.     return 1
 4.   f(2)
 5.     f(0)
 6.       return 0
 7.     f(1)
 8.       return 1
 9.     return 1 + 0
10.  return 1 + 1

这篇关于递归-一条语句中有两个调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆