输入整数n,计算1*2*…*n的代码
时间: 2023-12-03 15:02:52 浏览: 38
以下是两种计算1*2*...*n的代码:
```c++
// 方法一:使用for循环
#include <iostream>
using namespace std;
int main() {
int n, result = 1;
cin >> n;
for (int i = 1; i <= n; i++) {
result *= i;
}
cout << result << endl;
return 0;
}
```
```c++
// 方法二:使用递归
#include <iostream>
using namespace std;
int factorial(int n) {
if (n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int n;
cin >> n;
cout << factorial(n) << endl;
return 0;
}
```
相关问题
python计算1*2*3*n的代码
你可以使用循环来计算1*2*3*...*n的结果。以下是一个使用Python编写的示例代码:
```python
def calculate_factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
n = int(input("请输入一个正整数n:"))
factorial = calculate_factorial(n)
print(f"{n}的阶乘为:{factorial}")
```
这段代码定义了一个名为`calculate_factorial`的函数,它接受一个正整数n作为参数,并使用循环计算1*2*3*...*n的结果。然后,通过调用该函数并传入用户输入的值n,最后打印出计算结果。
c#用 while 用户输入一个整数 计算1*2*…*n的乘积结果
在C#中,可以使用while循环来实现用户输入一个整数n,并计算1*2*...*n的乘积结果。下面是一个示例代码:
```csharp
using System;
class Program
{
static void Main(string[] args)
{
Console.Write("请输入一个整数n:");
int n = Convert.ToInt32(Console.ReadLine());
int result = 1;
int i = 1;
while (i <= n)
{
result *= i;
i++;
}
Console.WriteLine("1*2*...*n的乘积结果为:" + result);
// 相关问题
Console.WriteLine("
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)