首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

斐波纳切递归有关问题

2012-09-17 
斐波纳切递归问题The Fibonacci numbers Fn are defined recursively as follows:F0 1F1 1Fn Fn-1 +

斐波纳切递归问题
The Fibonacci numbers Fn are defined recursively as follows:
F0 = 1
F1 = 1
Fn = Fn-1 + Fn-2
1.Write a recursive function, which calculates a Fibonacci number Fn. The function receives n as a parameter.写一个递归函数,计算Fn的数值,函数用n做参数
2. How many times does the function call itself, when n = 5? 当n=5的时候,这个递归函数调用自身的次数是几次?
3. What is the maximum number of parameters n simultaneously allocated on the processor stack. 
参数n同时分配到处理器堆栈的最大数量是多少?

第一题这个函数我写出了是:
int f(int n){
if(n==0||n==1)
return 1;
else
return(f(n-2)+f(n-1));
}

但是问题2,3的答案是什么我不确定,答案是多少? 还有3问的是什么意思我不太理解?求助,谢啦


[解决办法]
第二个问题你用一个全局变量就可以了。比如:

C/C++ code
#include <stdio.h>int counter = 0;int f(int n){    ++counter;    if(n == 0 || n == 1)        return 1;    else        return(f(n-2)+f(n-1));}int main(int argc, char* argv[]){    printf("%s = %d, f was executed %d times\n", "f(5)", f(5), counter);    return 0;}
[解决办法]
探讨
2,3楼都很牛,谢谢,那第三题如何解啊?

热点排行