将循环打印到 WINdows 表单中的单个标签控件

如何使用 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();  

   }

}


牛魔王的故事
浏览 215回答 1
1回答

墨色风雨

问题在于nFactorial.Text = factorial.ToString();&nbsp;您正在覆盖每个循环迭代的 nFactorial。你想要的(我假设)是附加文本,所以你想做这样的事情(格式化你想要的格式):nFactorial.Text += factorial.ToString() + Environment.NewLine; // Environment.NewLine to display each value on a separate line, again format how you'd like请注意,正如 Selman Genç 所提到的,您需要使用long而不是int(更改Int32为 long):long facOut, factorial, number;long num = 20;把它们放在一起:private void nFactorial_Click(object sender, EventArgs e){&nbsp; &nbsp; long facOut, factorial, number;&nbsp; &nbsp; long num = 20;&nbsp; &nbsp; factorial = num;&nbsp; &nbsp; for (facOut = num - 1; facOut >= 1; facOut--)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp;factorial *= facOut;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp;nFactorial.Text += factorial.ToString() + Environment.NewLine;&nbsp;&nbsp;&nbsp; &nbsp; }}编辑:好的,你正在向后循环。你需要向上而不是向下工作。试试这个:private void nFactorial_Click(object sender, EventArgs e){&nbsp; &nbsp; long facOut, factorial;&nbsp; &nbsp; long num = 20;&nbsp; &nbsp; factorial = 1;&nbsp; &nbsp; for (facOut = 1; facOut <= num; facOut++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; factorial *= facOut;&nbsp; &nbsp; &nbsp; &nbsp; tb.Text += factorial.ToString() + Environment.NewLine;&nbsp; &nbsp; }}注意:如果要跳过1,请facOut = 2在for循环中设置。
打开App,查看更多内容
随时随地看视频慕课网APP