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

关于一个递归算法有关问题,求教

2012-05-01 
关于一个递归算法问题,求教3. 一列数的规则如下: 1、1、2、3、5、8、13、21、34...... 求第30位数是多少, 用递归算

关于一个递归算法问题,求教
3. 一列数的规则如下: 1、1、2、3、5、8、13、21、34...... 求第30位数是多少, 用递归算法实现。

[解决办法]

探讨
方法①:【递归调用】

C# code


public int Foo(int i)
{
if (i < 0) return 0;

else if (i > 0 &amp;&amp; i <= 2) return 1;

else return Foo(i - 1) + Foo(i ……

[解决办法]
惭愧,还真不知道那叫斐波那契数列,学习了。我算的结果是832040
? int[] ints=new int[30];
? ints[0] = 1;
? ints[1] = 1;
? int c = 0;
? for (int i = 2; i < 30; i++)
? {
? ints[i]=ints[i-1]+ints[i-2];
? c = ints[i];
? }
? Console.WriteLine(c);
[解决办法]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 实验1
{
? class f1
? {?
? int s=0;
? public int f(int n)
? {
? if (n == 0 | n == 1)
? {
? s = 1;
? return s;
? }
? else
? {
? s = f(n - 1)+f(n - 2);

? } ?
? return s; ?
? } ?
? ?
? }
? class Program
? {
? static void Main(string[] args)
? {
? int a;
? f1 one = new f1();
? a= one.f(6);
? Console.WriteLine(a);
? ?
? }
? }
}
[解决办法]
楼主请看下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 递归
{
? class Program
? {
? static void Main(string[] args)
? {
? // 一列数的规则如下: 1、1、2、3、5、8、13、21、34...... 求第30位数是多少, 用递归算法实现。
? int n = Sum(30);
? Console.WriteLine(n);
? Console.ReadKey();
? }

? static int Sum(int num)
? {
? int sum = 1;
? for (int i = num; i >=2; i--)
? {
? sum = Sum(num - 1) + Sum(num - 2);
? }
? return sum;
? }
? }
}

热点排行