write a C program to run factorial
时间: 2024-06-14 11:06:18 浏览: 7
以下是一个用C语言编写的计算阶乘的程序:
```c
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
```
这个程序通过递归的方式计算给定数字的阶乘。它首先定义了一个名为`factorial`的函数,该函数接受一个整数参数`n`并返回其阶乘。然后,在`main`函数中,它要求用户输入一个数字,并调用`factorial`函数来计算并打印出该数字的阶乘。
相关问题
Write a C program to find the sum of the series 1! + 2! + 3! + 4! + 5! using the function
以下是一个C程序,用于使用函数找到序列1!+ 2!+ 3!+ 4!+ 5!的总和:
```c
#include <stdio.h>
int factorial(int num); // 声明函数
int main() {
int i, n = 5, sum = 0;
for (i = 1; i <= n; i++) {
sum += factorial(i); // 调用函数
}
printf("The sum of the series is: %d", sum);
return 0;
}
int factorial(int num) { // 定义函数
int i, fact = 1;
for (i = 1; i <= num; i++) {
fact *= i;
}
return fact;
}
```
c语言factorial函数
下面是使用递归方式实现的C语言factorial函数:
```c
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int n = 5;
int result = factorial(n);
printf("%d! = %d\n", n, result);
return 0;
}
```
输出:
```
5! = 120
```
在这个例子中,我们定义了一个factorial函数,它接受一个整数n作为参数,并返回n的阶乘。如果n为0,则返回1,否则返回n乘以factorial(n-1)的结果。在main函数中,我们调用了factorial函数来计算5的阶乘,并将结果打印到控制台。
相关推荐
![](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)