如何写出所有用于计算阶乘的整数

本文关键字:阶乘 整数 计算 用于 何写出 | 更新日期: 2023-09-27 18:03:23

现在我将4! = 24输出到消息框中。

我要做的是把所有在计算n时相乘的整数加起来,所以如果我输入4,我想得到4! = 1 x 2 x 3 x 4 = 24,而不是4! = 24

代码:

private void calculateButton_Click(object sender, EventArgs e)
{
    int userNumber = 0;
    double factorialNumber = 1;
    int.TryParse(numberInputTextBox.Text, out userNumber);
    if (userNumber > 0)
    {
        for (int countFactorial = 1; countFactorial <= userNumber; countFactorial++)
        {
            factorialNumber *= countFactorial;
        }
        MessageBox.Show(userNumber + "! = " + factorialNumber.ToString("n0"));
        resetButton.Focus();
    }
    else
    {
        MessageBox.Show("The factorial value entered must be an integer.");
        numberInputTextBox.Text = "";
        numberInputTextBox.Focus();
    }
}

如何写出所有用于计算阶乘的整数

您可以将数字从1到userNumber放入List<int> nums(例如),然后使用var numsStr = string.Join(" x ", nums);获得字符串1 x 2 x 3 x 4

例子:
if (userNumber > 0)
    {
        List<int> nums = new List<int>();
        for (int countFactorial = 1; countFactorial <= userNumber; countFactorial++)
        {
            factorialNumber *= countFactorial;
            nums.Add(countFactorial);
        }
        
        var numsStr = string.Join(" x ", nums);            
        var result = string.Format("{0} ! = {1} = {2}", userNumber, numsStr, factorialNumber.ToString("n0"));
        MessageBox.Show(result);
        resetButton.Focus();
    }