C#用递归算法实现:一列数的规则如下: 1、1、2、3、5、8、13、21、34,求第30位数是多少
作者:Robin 时间:2023-12-23 01:22:51
方法一:递归算法
/// <summary>
/// 一列数的规则如下: 1、1、2、3、5、8、13、21、34求第30位数是多少, 用递归算法实现。(C#语言)
/// </summary>
/// <param name="pos"></param>
/// <returns></returns>
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;
}
标签:C#,递归算法
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
使用Java设置字型和颜色的方法详解
2023-04-14 05:09:23
![](https://img.aspxhome.com/file/2023/9/72579_0s.jpg)
Unity Shader实现模糊效果
2021-07-22 02:42:57
![](https://img.aspxhome.com/file/2023/7/104247_0s.jpg)
Java多线程run方法中直接调用service业务类应注意的问题及解决
2021-12-28 19:51:46
![](https://img.aspxhome.com/file/2023/0/92680_0s.png)
Android重要控件SnackBar使用方法详解
2022-11-10 04:49:41
android通过servlet上传文件到服务器
2021-10-07 05:44:02
![](https://img.aspxhome.com/file/2023/1/86011_0s.jpg)
Android检查手机网络状态及网络类型的方法
2023-12-03 19:35:49
Java初学者常问的问题(推荐)
2023-05-29 05:41:51
java计算给定字符串中出现次数最多的字母和该字母出现次数的方法
2022-01-13 03:00:04
Spring源码完美导入IDEA的过程
2023-05-13 14:11:50
![](https://img.aspxhome.com/file/2023/3/80323_0s.jpg)
C# dynamic关键字的使用方法
2023-02-26 08:40:01
C#移除所有事件绑定的方法
2023-07-25 11:00:52
Android应用开发中Fragment间通信的实现教程
2023-02-23 18:06:46
Compare And Swap底层原理及代码示例详解
2022-10-10 16:06:18
![](https://img.aspxhome.com/file/2023/8/125658_0s.png)
JAVA 实现磁盘文件加解密操作的示例代码
2023-11-15 00:13:06
Eclipse 2020-06 汉化包安装步骤详解(附汉化包+安装教程)
2021-05-31 09:26:37
![](https://img.aspxhome.com/file/2023/8/112048_0s.jpg)
Java进阶知识之反射的概念与获取方法
2023-12-09 19:09:14
![](https://img.aspxhome.com/file/2023/8/108418_0s.jpg)
C#画图之饼图折线图的实现方法
2021-12-05 22:26:13
JAVA中实现链式操作(方法链)的简单例子
2022-12-16 00:54:50
MyBatis中映射文件的使用案例代码
2021-09-02 23:55:41
![](https://img.aspxhome.com/file/2023/0/60910_0s.png)
java配置多个过滤器优先级以及几个常用过滤器操作
2023-12-17 01:52:10