Title: f(n)=f(n-1)+f(n-2)
f(0)=2; f(1)=3, find f(40)
This problem requires the use of function recursion to calculate,
We know f(0) and f(1) ,
Then by calculation, f(2) is f(0) + f(1) = 2 + 3 = 5;
Create a function F, the input value is int n , and the return value is int;
static int F(int n)
{
}
Return the formula directly in the function:
return F(n - 1) + F(n - 2);//函数递归调用
At this time, there needs to be a condition to terminate the recursion, write f (0) and f(1) ;
if (n == 0) return 2; //终止递归的条件
if (n == 1) return 3;
Call the function F in the main function, and the obtained res value is the value of f(40), and calculate the value of f(2) as a comparison:
static void Main(string[] args)
{
int res = F(40);
int res2 = F(2);
}
The source code is as follows:
using System;
//02
//f(n)=f(n-1)+f(n-2) f(0)=2 f(1)=3 ,用程序求得f(40)
namespace _05s
{
class Program
{
static void Main(string[] args)
{
int res = F(40);
int res2 = F(2);
Console.WriteLine("f40:" + res);
Console.WriteLine("f2:" + res2);
}
static int F(int n)
{
if (n == 0) return 2; //终止递归的条件
if (n == 1) return 3;
return F(n - 1) + F(n - 2);//函数递归调用
}
}
}
The printed results are as follows:
Sanlian~