在递归中使用按引用传递 [英] Use pass by reference in recursion

查看:40
本文介绍了在递归中使用按引用传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int f(int &x, int c) 
{
     c  = c - 1;
     if (c == 0) return 1;
     x = x + 1;
     return f(x, c) * x;
} 

int x = 5;
cout << f(x,5);

在上面的例子中,可供选择的四个可能的答案是:

In the example above the four possible answers to choose from are:

  1. 3024
  2. 6561
  3. 55440
  4. 161051

函数 f(int &x, int c) 在第一次调用后被调用四次,直到它返回结果为 6561.我的猜测是 3024 但我错了.即使通过引用传递的 x 变量在 f(int &x, int c) 的每次调用中都会递增并取值 6->;7->8->9 分别这个递归的最终结果等于9^4.

Function f(int &x, int c) is called four times after the first call before it reaches the base case where it returns the result which is 6561. My guess was 3024 but I was wrong. Even if the x variable which is passed by reference increments in each call of f(int &x, int c) and takes the values 6->7->8->9 respectively the final result of this recursion is equal to 9^4.

所以我的问题是:变量 x 是通过引用传递的,并且在达到基本情况时等于 9.这是否意味着递归的所有阶段都会为变量 x 设置这个值,即使它们在被调用时具有不同的值?

So my question is: Variable x is passed by reference and is equal to 9 when it reaches the base case. Does that mean that all the stages of recursion will have this value for variable x even if they had a different value when they've been called?

推荐答案

不,有四个以上的答案可供选择.

No, there are more than four answers to choose from.

递归函数调用的x和乘法右边的x的取数,没有相互排序;因此评估顺序未指定.

The fetch of x for the recursive function call, and the fetch of x for the right hand side of multiplication, is not sequenced with each other; and as such the evaluation order is unspecified.

这并不意味着评估顺序将是某个特定的评估顺序,只需弄清楚即可.这意味着最终结果可以:

This doesn't mean that the evaluation order would be some particular evaluation order, and it's only necessary to figure it out. This means that the final results can:

  1. 因编译器而异.

  1. Vary depending on the compiler.

每次执行此程序时都不同.

Vary each time this program executes.

每个单独的递归调用的评估顺序也可能不同.每个递归调用最终也可以使用不同的评估顺序.未指定"的意思是未指定".任何可能性都有可能发生.每一次.

The evaluation order may also be different for each individual recursive call. Each recursive call can end up using a different evaluation order, too. "Unspecified" means "unspecified". Any possibility can happen. Each individual time.

我没有费心在这里计算所有实际的可能性.最好将自己的时间投入到应该正常工作的事情上,而不是花在显然永远无法正常工作的事情上.

I didn't bother to calculate all actual possibilities here. It's better to invest one's own time on something that should work properly, instead of on something that obviously can never work properly.

如果你想要一个特定的评估顺序,它会是这样的:

If you want a specific evaluation order, it's going to be either this:

int y=x;

return f(x, c) * y;

或者这个:

int y=f(x, c);

return y * x;

此评估顺序现已指定.

这篇关于在递归中使用按引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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