功能仿真 [英] Simulation of a Function

查看:102
本文介绍了功能仿真的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int fib(n) {
 if(n == 0)
   return 0
 if(n == 1)
   return 1
 return fib(n-1)+fib(n-2) }


模拟fib(5)
<罢工>这是我的面试问题.我不知道真正的答案是什么!您可以回答这个问题吗?


Simulate fib(5)
This was my interview question. I don''t know what the real answer is ! Can you help me by answering this question ?

推荐答案

fib(5) =                 fib(4)                +              fib(3)
           fib(3)          +       fib(2)            fib(2)    +    fib(1)
   fib(2)    +    fib(1)      fib(1)  +  fib(0)  fib(1) + fib(0)
fib(1) + fib(0)



您要做的就是替换,直到满足递归终止条件为止:

fib(1)== 1和fib(0)== 0所以结果是:5

干杯,



All you have to do is substitution until the recursion terminating conditions are hit:

fib(1) == 1 and fib(0) == 0 so the result is: 5

Cheers,


请注意:这是C ++. "="表示分配,而不是相等检查.要检查两个对象是否相等,请使用"==".

另一个错误是这样的:如果n == 1fib(n - 2)fib(-1),则不需要.因此,您需要三个分支:n == 0时,需要再增加1个分支(在最后一种情况下,请使用else;这是n-2有效的唯一情况.

另外,在每个语句后添加;".

我的想法是,如果仅修复这两个错误,则代码将起作用.
您是否不考虑更普遍的情况,即先发成员是任意的种子值"?然后您需要修改代码.

注意 :我发布了此信息后,OP修复了Question中的代码.

—SA
Please pay attention: this is C++. "=" means assignment, not the check for being equal. To check is two objects are equal, use "==".

Another bug is this: if n == 1, fib(n - 2) is fib(-1), which you don''t want. Hence, you need three branches: for n == 0, 1 more (in the last case, use else; this is the only case when n-2 is valid.

Also, add '';'' after each statement.

I thing, if you fix just these two bugs, you code will work.
Don''t you consider more general case where first to members are arbitrary "seed value"? Then you need to modify the code.

Note: OP fixed the code in Question after I posted this.

—SA


这篇关于功能仿真的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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