在Windows窗体中将循环打印到单个标签控件

时间:2018-09-07 16:01:50

标签: c#

如何使用for循环从1-20打印每个阶乘?

输出应与Windows窗体应用程序中的相同标签相同。

我尝试使用此方法,但没有得到想要的结果(这是垂直打印从1到20的所有阶乘,即((2,6,24,)),相反,我看到的值是-2102162736

private void nFactorial_Click(object sender, EventArgs e)
{
   long facOut, factorial;
   long num = 20;
   factorial = num;

   for (facOut = num - 1; facOut >= 1; facOut--)
   {
       factorial *= facOut;         
       nFactorial.Text += factorial.ToString();  
   }
}

1 个答案:

答案 0 :(得分:2)

问题出在

nFactorial.Text += factorial.ToString() + Environment.NewLine; // Environment.NewLine to display each value on a separate line, again format how you'd like

您将在每次循环迭代中覆盖nFactorial。

(我假设)您想要添加文本,因此您想要执行以下操作(格式化所需的格式):

long

请注意,正如SelmanGenç所述,您需要使用int而不是Int32(将long facOut, factorial, number; long num = 20; 更改为long):

private void nFactorial_Click(object sender, EventArgs e)
{
    long facOut, factorial, number;
    long num = 20;
    factorial = num;

    for (facOut = num - 1; facOut >= 1; facOut--)
    {
       factorial *= facOut;         
       nFactorial.Text += factorial.ToString() + Environment.NewLine;  
    }
}

将它们放在一起:

private void nFactorial_Click(object sender, EventArgs e)
{
    long facOut, factorial;
    long num = 20;
    factorial = 1;

    for (facOut = 1; facOut <= num; facOut++)
    {
        factorial *= facOut;
        tb.Text += factorial.ToString() + Environment.NewLine;
    }
}

编辑:好的,您正在向后循环。您需要努力而不是失败。试试这个:

facOut = 2

注意:如果要跳过1,请在for循环中设置Dictionary<string, int>