栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

C#用递归算法实现:一列数的规则如下: 1、1、2、3、5、8、13、21、34,求第30位数是多少

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C#用递归算法实现:一列数的规则如下: 1、1、2、3、5、8、13、21、34,求第30位数是多少

方法一:递归算法

/// 
/// 一列数的规则如下: 1、1、2、3、5、8、13、21、34求第30位数是多少, 用递归算法实现。(C#语言)
/// 
/// 
/// 
public int GetNumberAtPos(int pos)
{
  if(pos==0||pos==1)
  {
    return 1;
  }
  int res = GetNumberAtPos(pos - 1) + GetNumberAtPos(pos - 2);
  return res;
}

方法二:不用递归

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

namespace Test
{
  public class Class1
  {
    private ArrayList list = new ArrayList();

    public Class1()
    {
    }

    public Class1(int num)
      : base()
    {
      int i;

      for (i = 1; i <= num; i++)
      {
 list.Add(Calculation(i));
      }
    }

    private int Calculation(int num)
    {
      if (num == 1 || num == 2)
 return 1;
      else
 return Convert.ToInt32(list[num - 2]) + Convert.ToInt32(list[num - 3]);
    }

    public int Calculation()
    {
      return Convert.ToInt32(list[list.Count - 1]);
    }
  }

  public class test
  {
    public static void Main()
    {
      int j;
      int num;
      for (j = 1; j < 100; j++)
      {
 Console.WriteLine("你要计算第多少位:");
 string readstr;
 readstr = Console.ReadLine();
 if (!string.IsNullOrEmpty(readstr))
 {
   if (int.TryParse(readstr, out num))
   {
     if (num < 1)
continue;
     else
     {
Class1 c1 = new Class1(num);
Console.WriteLine(c1.Calculation());
     }
   }
   else
   {
     continue;
   }
 }
 else
 {
   break;
 }
      }
    }
  }
}

方法三:用循环实现

public long getNumber(int pos)
{
  long one = 1;
  long two = 1;
  if (pos == 0 || pos == 1)
  {
    return 1;
  }
  int i = 3;
  long sum = 1;
  while (i <= pos)
  {
    sum = one + two;
    one = two;
    two = sum;
    i++;
  }
  return sum;
}

以上就是本文的全部内容,希望能给大家一个参考,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/124168.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号