用c语言计算1!+2!+3!+……+n!
时间: 2023-05-21 16:03:28 浏览: 75
以下是用 C 语言计算 1! 2! 3! …… n! 的代码:
```c
#include <stdio.h>
int main() {
int n, i, j, factorial;
printf("请输入一个正整数 n:");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
factorial = 1;
for (j = 1; j <= i; j++) {
factorial *= j;
}
printf("%d! = %d\n", i, factorial);
}
return 0;
}
```
这个程序会让用户输入一个正整数 n,然后计算并输出 1!、2!、3!、……、n! 的值。
相关问题
c语言计算 1!+2!+3!+……+10!
以下是两种C语言计算1!+2!+3!+……+10!的例子:
1.使用上一个计算的阶乘进行相乘,避免每次都重新计算阶乘:
```c
#include <stdio.h>
int main() {
int i = 0;
int result = 1;
int sum = 0;
for (i = 1; i < 11; i++) {
result *= i; //result会保留上一个的阶乘进行相乘
sum += result;
}
printf("1!+2!+3!+……+10!:%d", sum);
return 0;
}
```
2.每次都重新计算阶乘,避免结果越来越大:
```c
#include <stdio.h>
int main() {
int i = 0;
int j = 0;
int n = 0;
int sum = 0;
int result = 1;
for ( i = 1; i < 11; i++) {
result = 1; //计算下一个阶乘时,要将result初始化
for (j = 1; j <= i; j++) {
result *= j;
}
sum += result;
}
printf("1!+2!+3!+……+10!:%d", sum);
return 0;
}
```
C语言求1!+2!+……+n!
编写一个函数fun,用于计算1!+2!+3!+ …… +n!的和。在main函数中,从键盘输入n值,并输出运算结果。下面是fun函数的代码实现:
```c
int fun(int n) {
int sum = 0;
int i, j, temp;
for (i = 1; i <= n; i++) {
temp = 1;
for (j = 1; j <= i; j++) {
temp *= j;
}
sum += temp;
}
return sum;
}
```
在main函数中,我们可以这样调用fun函数:
```c
int main() {
int n, result;
printf("请输入n的值:");
scanf("%d", &n);
result = fun(n);
printf("1!+2!+3!+...+n!的和为:%d\n", result);
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)