目录
1.斐波纳契数列
2.迭代一次产生1个新的通项
3.迭代一次产生2个新的通项
1.斐波纳契数列
斐波纳契数列的定义是,它的第一项和第二项均为1,以后各项都为前两项之和。
公式如下:
F(n) = F(n-1) + F(n-2)
其中,F(1) = 0, F(2) = 1。
2.迭代一次产生1个新的通项
// 用迭代的方法求斐波那契数列通项
namespace _147_1
{
class Program
{
static void Main(string[] args)
{
ArgumentNullException.ThrowIfNull(args);
int n = 10;
int a = 0, b = 1, c = 0;
string fibSequence = "";
for (int i = 1; i <= n; i++)
{
c = a + b;
a = b;
b = c;
fibSequence += c.ToString() + (i < n ? ", " : "");
}
Console.WriteLine("第{0}项斐波那契数列的值为:{1}", n, c);
Console.WriteLine("斐波那契数列的前{0}项为:{1}", n, fibSequence);
}
}
}
//运行结果:
/*
第10项斐波那契数列的值为:89
斐波那契数列的前10项为:1, 2, 3, 5, 8, 13, 21, 34, 55, 89
*/
3.迭代一次产生2个新的通项
// 斐波纳契数列通项
namespace _147
{
public partial class Form1 : Form
{
private ListBox? listBox1;
private Label? label1;
private TextBox? textBox1;
private Button? button1;
public Form1()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
Load += Form1_Load;
}
private void Form1_Load(object? sender, EventArgs e)
{
//
// listBox1
//
listBox1 = new ListBox
{
FormattingEnabled = true,
ItemHeight = 17,
Location = new Point(12, 12),
Name = "listBox1",
Size = new Size(250, 191),
TabIndex = 0
};
//
// label1
//
label1 = new Label
{
AutoSize = true,
Location = new Point(12, 217),
Name = "label1",
Size = new Size(44, 17),
TabIndex = 1,
Text = "数字:"
};
//
// textBox1
//
textBox1 = new TextBox
{
Location = new Point(71, 211),
Name = "textBox1",
Size = new Size(100, 23),
TabIndex = 2
};
//
// button1
//
button1 = new Button
{
Location = new Point(186, 211),
Name = "button1",
Size = new Size(75, 23),
TabIndex = 3,
Text = "计算",
UseVisualStyleBackColor = true
};
button1.Click += Button1_Click;
//
// Form1
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(274, 246);
Controls.Add(button1);
Controls.Add(textBox1);
Controls.Add(label1);
Controls.Add(listBox1);
Name = "Form1";
Text = "Form1";
}
private void Button1_Click(object? sender, EventArgs e)
{
listBox1?.Items.Clear();//清空ListBox控件
int a = 1, b = 1; //定义变量
int p; //循环次数
try
{
p = Convert.ToInt32(textBox1!.Text);
}
catch //出现错误
{
MessageBox.Show("请输入数值型数据");
textBox1!.Text = "15";
return;
}
int n;
for (n = 1; n <= p; n++)//每次遍历添加2个项目
{
listBox1!.Items.Add(a.ToString());//输出数值
listBox1.Items.Add(b.ToString());//输出数值
a += b;//获取前两个数的和
b += a;//获取前两个数的和
}
}
}
}