目录
????????递归算法在程序设计中被广泛应用,递归是方法在运行中直接或间接调用自身而产生的重入现象,它是计算机科学的一个重要概念,而且在算法的世界中占有着重要的位置,使用递归方法可以使代码变得更加简洁和清晰。?
????????在C#中,每建立一条线程都会被分配大约1MB大小的地址空间,由于线程栈有固定的大小,如果进行递归的层次太深,有可能会出现溢出。
// 递归计算数列a(n)=a(n-1)+a(n-2)
namespace _032
{
public partial class Form1 : Form
{
private Label? label1;
private TextBox? textBox2;
private TextBox? textBox1;
private Button? button1;
private GroupBox? groupBox1;
public Form1()
{
InitializeComponent();
Load += Form1_Load;
}
private void Form1_Load(object? sender, EventArgs e)
{
//
// label1
//
label1 = new Label
{
AutoSize = true,
Location = new Point(12, 22),
Name = "label1",
Size = new Size(43, 17),
TabIndex = 0,
Text = "输入数列第n项:"
};
//
// textBox1
//
textBox1 = new TextBox
{
Location = new Point(115, 22),
Name = "textBox1",
Size = new Size(100, 23),
TabIndex = 1
};
//
// textBox2
//
textBox2 = new TextBox
{
Location = new Point(12, 51),
Name = "textBox2",
Size = new Size(180, 23),
TabIndex = 3,
Visible = false
};
//
// button1
//
button1 = new Button
{
Location = new Point(230, 22),
Name = "button1",
Size = new Size(70, 23),
TabIndex = 2,
Text = "计算",
UseVisualStyleBackColor = true
};
button1.Click += Button1_Click;
//
// groupBox1
//
groupBox1 = new GroupBox
{
Location = new Point(12, 12),
Name = "groupBox1",
Size = new Size(310, 87),
TabIndex = 3,
TabStop = false,
Text = "递归计算数列a(n)=a(n-1)+a(n-2)"
};
groupBox1.Controls.Add(label1);
groupBox1.Controls.Add(button1);
groupBox1.Controls.Add(textBox1);
groupBox1.Controls.Add(textBox2);
groupBox1.SuspendLayout();
//
// Form1
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(334, 111);
Controls.Add(groupBox1);
Name = "Form1";
StartPosition = FormStartPosition.CenterScreen;
Text = "递归算法";
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
}
private void Button1_Click(object? sender, EventArgs e)
{
textBox2!.Visible = true;
if (int.TryParse(textBox1!.Text, out int Input_int))//为变量赋值
{
textBox2!.Text = //输出计算结果
"计算结果为:" + Get(Input_int).ToString();
}
else
{
MessageBox.Show("请输入正确的数值!", "提示!"); //提示输入正确数值
}
}
/// <summary>
/// 递归算法
/// </summary>
/// <param name="i">数列的第n项n值</param>
/// <returns>计算结果</returns>
static int Get(int i)
{
if (i <= 0) //判断数值是否小于0
return 0; //返回数值0
else if (i >= 1 && i <= 2) //判断位数是否大于等于0并且小于等于2
return 1; //返回数值1
else //如果不满足上述条件执行下面语句
return Get(i - 1) + Get(i - 2); //返回指定位数前两位数的和
}
}
}
?