Fibonacci数列 前n项求和
public int FibonacciSum(int aVal)
{
int sum = 0;
if (aVal == 0)
{
return 0;
}
if (aVal == 1)
{
return sum = 1;
}
else if (aVal == 2)
{
return sum = 2;
}
else
{
int[] Fibo = new int[aVal];
for (int i = 0; i < aVal; i++)
{
Fibo[0] = 1;
Fibo[1] = 1;
for (int j = 3; j <= aVal; j++)
{
Fibo[j - 1] = Fibo[j - 2] + Fibo[j - 3];
}
sum = sum + Fibo[i];
}
}
return sum;
}
控制台程序实现
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleUtilities
{
public class FibonacciSum
{
public static void SumFibonacci()
{
Console.WriteLine("请输入要求的项数N:");
//接收控制台传来的数据
string result = Console.ReadLine();
int n = Convert.ToInt32(result);
int[] f = new int[n]; //定义一个整形数组用于存放斐波那契数,好像用整形当项数N大于45时会发生溢出,产生错误结果
int sum = 0; //存放前N项之和
//处理特殊情况n<=0
if (n <= 0)
{
Console.WriteLine("项数必须是大与0的整数!");
}
//处理特殊情况n=1
else if (n == 1)
{
sum = 1;
Console.WriteLine("斐波那契数列如下:\n1");
Console.WriteLine("前" + n + "项之和为: " + sum);
}
//处理特殊情况n=2
else if (n == 2)
{
sum = 2;
Console.WriteLine("斐波那契数列如下:\n1 1");
Console.WriteLine("前" + n + "项之和为: " + sum);
}
//处理一般情况n>=3
else
{
Console.WriteLine("斐波那契数列如下:");
for (int i = 0; i < f.Length; i++)
{
f[0] = 1;
f[1] = 1;
for (int j = 3; j <= n; j++)
{
f[j - 1] = f[j - 2] + f[j - 3]; //斐波那契数列各项之间的关系,不能用f[j]=f[j-1]+f[j-2],会发生数组越界异常
}
Console.WriteLine(f[i] + "\t");
sum = sum + f[i];
if ((i + 1) % 12 == 0)
{ //控制12个数为一行
Console.WriteLine();
}
}
Console.WriteLine(); //输出一个空行再显示前N项之和
Console.WriteLine("前" + n + "项之和为: " + sum);
Console.Read();
}
}
}
}