递归函数的输出 [英] Output of a Recursion Function

查看:224
本文介绍了递归函数的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在经历一些关于递归的问题。我很难接受递归。

这是一个问题,我们必须评估以下代码的输出: -

I was going through some question about recursion . I am having a hard time with recursion .
Here is a question ,we have to evaluate the output of following code :-

On recursion, value of f(513,2)
 
 if(n<0)
   return 0;
 else
   return ( n%10 + f(n/10, 2) )





现在从512开始



我们得到回报(3 + f(51,2)

再次我们有(3 + 1 + f(5,2)

再次(4 + 5 + f(0,2))

我们有(4 + 5 + 0)



有了这个我得到结果= 9.是不是?



Now starting with 512

we get return ( 3 + f(51,2)
again we have (3+1+f(5,2)
again (4+5+f(0,2))
we have (4+5+0)

With this i get the result =9 . Is is right ?

推荐答案

是的 - 但最简单的事情就是尝试它。编写一个简单的C函数,然后用你的函数调用它通过跟随调试器中的代码执行来查看它的功能。



要回答你的补充问题,否 - 如果你通过,它将不会永远循环这是一个负值,因为测试

Yes - but the simplest thing to do is try it. Write a simple C function, and call it with your values. See what it does, by following the code execution in the debugger.

To answer your supplementary question, "No" - it will not loop forever if you pass it a negative value, because the test
if (n<0)

终止在负值上执行函数而不是再进一步递归。

terminates execution of the function on a negative value instead of recursing any further.


可能9是正确的。但问题不是:



1.代码的第一行不是C代码 - 我认为它是文本描述的一部分或只是定义输入。 br />
2.你没有(正式)提供函数f的定义 - 我假设代码的最后4行描述它。 (并且我会默默地添加那个缺少';'的结尾)

3.但是,f应该采用2个参数,但是所说的代码只使用一个 - 第二个参数始终保持为值2 !为什么?



您应该按照描述的准确性进行处理;编程就是让计算机理解你的意图,计算机程序无法准确猜出上述情况。



同样,如果你问一个关于编程的问题,您对问题的描述越不准确,您得到的答案就越有可能无法使用。
Probably 9 is right. But the question is not:

1. The first line of the code is not C code - I assume it's part of the textual description or just defines the input.
2. You did not (formally) provide the definition of function f - I assume the last 4 lines of the code describe it. (and I'll silently add that missing ';' at the end)
3. However, f should take 2 arguments, but said code only uses one - the second argument is always constant at value 2! Why is that?

You should work on the accuracy of your descriptions; programming is all about making computers understand your intentions, and none of the above could be accurately guessed by a computer program.

Similarly, if you ask a question about programming, the less accurate your description of the problem, the more likely any answer you get is unusable.


这篇关于递归函数的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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