如何在 C# 中使用递归在列表框中打印 1 到 n?
How do I print 1 to n in a listbox using recursion in C#?
我正在尝试编写一个程序,该程序使用递归循环遍历给定值并将其按顺序打印到列表框中。当我将 5 用于 n:
时,输出应该看起来像这样
1 2 3 4 5
但是,我想不出让我的程序运行的方法,我得到的任何其他来源都只使用控制台功能。
下面是我到目前为止的代码。我将不胜感激我能得到的任何帮助。
private void button1_Click(object sender, EventArgs e)
{
int n;
n = Convert.ToInt32(textBox1.Text);
int print = Print(1, n);
listBox1.Items.Add(print);
}
private static int Print(int order, int n)
{
if (n < 1)
{
return order;
}
n--;
return Print(order + 1, n);
}
嗯,我现在无法对此进行测试,但我希望我已经弄清楚了这个概念。
像这样的东西应该可以完成工作:
private void button1_Click(object sender, EventArgs e)
{
int n;
n = Convert.ToInt32(textBox1.Text);
PrintToListBox(listBox1, 1, n);
}
private static void PrintToListBox(ListBox listBox, int frm, int to)
{
listBox1.Items.Add(frm);
if (frm + 1 <= to)
{
PrintToListBox(listBox1, frm + 1, n);
}
return;
}
我会写成:
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
PrintToListBox(listBox1, 1, 5);
}
private void PrintToListBox(ListBox lb, int n, int max)
{
if (n <= max)
{
lb.Items.Add(n);
PrintToListBox(lb, n+1, max);
}
}
我正在尝试编写一个程序,该程序使用递归循环遍历给定值并将其按顺序打印到列表框中。当我将 5 用于 n:
时,输出应该看起来像这样1 2 3 4 5
但是,我想不出让我的程序运行的方法,我得到的任何其他来源都只使用控制台功能。
下面是我到目前为止的代码。我将不胜感激我能得到的任何帮助。
private void button1_Click(object sender, EventArgs e)
{
int n;
n = Convert.ToInt32(textBox1.Text);
int print = Print(1, n);
listBox1.Items.Add(print);
}
private static int Print(int order, int n)
{
if (n < 1)
{
return order;
}
n--;
return Print(order + 1, n);
}
嗯,我现在无法对此进行测试,但我希望我已经弄清楚了这个概念。
像这样的东西应该可以完成工作:
private void button1_Click(object sender, EventArgs e)
{
int n;
n = Convert.ToInt32(textBox1.Text);
PrintToListBox(listBox1, 1, n);
}
private static void PrintToListBox(ListBox listBox, int frm, int to)
{
listBox1.Items.Add(frm);
if (frm + 1 <= to)
{
PrintToListBox(listBox1, frm + 1, n);
}
return;
}
我会写成:
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
PrintToListBox(listBox1, 1, 5);
}
private void PrintToListBox(ListBox lb, int n, int max)
{
if (n <= max)
{
lb.Items.Add(n);
PrintToListBox(lb, n+1, max);
}
}