c#请编写程序,求出 n!【提示:n 的阶乘等于从 1 到 n 的乘积】,n 由键盘输入 n!=1*2*3…..*n?

如题所述

第1个回答  2024-01-22
```csharp
using System;
class Program
{
static void Main(string[] args)
{
Console.Write("请输入一个正整数n: ");
int n;
if (int.TryParse(Console.ReadLine(), out n) && n >= 0)
{
long factorial = CalculateFactorial(n);
Console.WriteLine($"{n}! 的值为: {factorial}");
}
else
{
Console.WriteLine("输入不合法,必须是非负整数!");
}
}
static long CalculateFactorial(int n)
{
long result = 1;
for (int i = 1; i <= n; i++)
{
result *= i;
// 当结果超出long类型的最大值时,可以提前结束循环并输出错误信息(可选)
if (result > long.MaxValue)
{
throw new OverflowException("计算结果超过了long类型的最大值!");
}
}
return result;
}
}
```
这个C#程序首先会提示用户输入一个正整数n,然后通过`CalculateFactorial`方法计算n的阶乘,并在控制台输出结果。注意,由于阶乘运算可能会导致数值过大超出`long`类型的最大值,所以在计算过程中加入了溢出检查(当结果大于`long.MaxValue`时抛出异常)。
相似回答