c#数的阶乘for while do-while
时间: 2024-09-25 11:13:31 浏览: 66
在 C# 中,计算一个数的阶乘可以使用 for、while 或 do-while 循环。以下是三种方法的示例:
1. **For循环**:
```csharp
public long Factorial(int number)
{
if (number < 0) throw new ArgumentException("Number must be non-negative.");
long factorial = 1;
for (int i = 1; i <= number; i++)
{
factorial *= i;
}
return factorial;
}
```
2. **While循环**:
```csharp
public long FactorialWhile(int number)
{
if (number < 0) throw new ArgumentException("Number must be non-negative.");
int current = 1;
long factorial = 1;
while (current <= number)
{
factorial *= current;
current++;
}
return factorial;
}
```
3. **Do-while循环**:
```csharp
public long FactorialDoWhile(int number)
{
if (number < 0) throw new ArgumentException("Number must be non-negative.");
bool continueLoop = true;
long factorial = 1;
do
{
factorial *= current;
current++;
} while (continueLoop && current <= number);
return factorial;
}
```
在上述代码中,`factorial`变量会保存计算出的阶乘结果。注意,对于大的数字,可能会超过 `long` 类型的最大值,这时需要考虑使用 `BigInteger` 类。
阅读全文