定义一个计算n!的函数int n,该函数可以供Int
时间: 2023-05-29 21:05:53 浏览: 50
def factorial(n: int) -> int:
"""
计算n的阶乘
"""
if n == 0:
return 1
else:
return n * factorial(n-1)
相关问题
定义一个计算n!的函数int n,该函数供int sum函数调用
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int sum(int n) {
int result = 0;
for (int i = 1; i <= n; i++) {
result += factorial(i);
}
return result;
}
c语言编写一个计算n!的函数
以下是一个简单的C语言函数,用于计算n的阶乘(n!):
```c
#include <stdio.h>
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
int n = 5;
int result = factorial(n);
printf("%d! = %d\n", n, result);
return 0;
}
```
在这个示例中,我们定义了一个名为`factorial`的函数,它接受一个整数n作为参数,返回n的阶乘。我们使用一个for循环来迭代从1到n的每个数字,并使用一个变量result来存储乘积。最后,我们返回这个乘积。
在main函数中,我们调用了`factorial`函数来计算5的阶乘,并将结果打印到控制台上。
相关推荐
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)