.输入整数n(n≥0),分别利用for循环,while循环、do—while循环求n!
时间: 2024-10-23 20:19:27 浏览: 42
当你需要计算一个非负整数 \( n \) 的阶乘 (n!),你可以使用 for 循环、while 循环或 do-while 循环来逐个相乘。下面我会为你展示如何使用这三种循环结构来实现。
### 1. For 循环
```csharp
int n;
Console.Write("请输入一个非负整数: ");
n = int.Parse(Console.ReadLine());
int factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= i;
}
Console.WriteLine($"{n}! 的阶乘是: {factorial}");
```
### 2. While 循环
```csharp
int n, factorial = 1;
Console.Write("请输入一个非负整数: ");
n = int.Parse(Console.ReadLine());
while (n > 0)
{
factorial *= n--;
}
Console.WriteLine($"{n}! 的阶乘是: {factorial}");
```
### 3. Do-While 循环
```csharp
int n, factorial = 1;
Console.Write("请输入一个非负整数: ");
n = int.Parse(Console.ReadLine());
do
{
factorial *= n;
n--;
} while (n > 0);
Console.WriteLine($"{n}! 的阶乘是: {factorial}");
```
以上代码都会先读取用户输入的整数 \( n \),然后根据所选择的循环结构计算 \( n!\) 并打印结果。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)