用c#编写计算n!,能捕捉算术溢出异常,并能输出产生溢出时的n值。(设n为int型)
时间: 2024-03-09 13:48:19 浏览: 25
可以使用`BigInteger`类型来避免算术溢出,同时使用`try-catch`语句捕捉溢出异常,代码如下:
```csharp
using System;
using System.Numerics;
class Program
{
static BigInteger Factorial(int n)
{
BigInteger result = 1;
for (int i = 1; i <= n; i++)
{
try
{
result *= i;
if (result < 0)
{
throw new OverflowException("Factorial overflow");
}
}
catch (OverflowException ex)
{
Console.WriteLine($"{ex.Message}: n = {i}");
return -1;
}
}
return result;
}
static void Main(string[] args)
{
int n = 25;
BigInteger result = Factorial(n);
if (result != -1)
{
Console.WriteLine($"{n}! = {result}");
}
}
}
```
在上面的代码中,我们使用`BigInteger`类型存储阶乘的结果,然后在每次乘法操作后判断结果是否小于0,如果小于0则说明发生了算术溢出,此时我们使用`throw`语句抛出一个`OverflowException`异常,然后在`catch`语句中捕获该异常并输出提示信息。最后的结果如果不为-1,则说明计算成功,输出阶乘的值。