c语言求1!+2!+3!+4!+5!代码加运行结果用while和for循环写
时间: 2023-11-27 19:47:12 浏览: 102
以下是使用while和for循环分别实现求1!+2!+3!+4!+5!的C语言代码及运行结果:
使用while循环实现:
```c
#include <stdio.h>
#include <stdlib.h>
int Factor(int n) //计算n的阶乘
{
int result = 1;
for (int i = 1; i <= n; i += 1) {
result *= i;
}
return result;
}
int Factorsum_while(int n) //计算1!+2!+3!+...+n!的和
{
int sum = 0;
int i = 1;
while (i <= n) {
sum += Factor(i);
i++;
}
return sum;
}
int main() {
int result = Factorsum_while(5); //n为5
printf("result = %d\n", result); //输出结果:result = 153
system("pause");
return 0;
}
```
使用for循环实现:
```c
#include <stdio.h>
#include <stdlib.h>
int Factor(int n) //计算n的阶乘
{
int result = 1;
for (int i = 1; i <= n; i += 1) {
result *= i;
}
return result;
}
int Factorsum_for(int n) //计算1!+2!+3!+...+n!的和
{
int sum = 0;
for (int i = 1; i <= n; i += 1) {
sum += Factor(i);
}
return sum;
}
int main() {
int result = Factorsum_for(5); //n为5
printf("result = %d\n", result); //输出结果:result = 153
system("pause");
return 0;
}
```
相关推荐
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)