gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:03:46 25 4
gpt4 key购买 nike

现在我有 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();
}

关于c# - 如何写出用于计算阶乘的所有整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31505175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com