C语言求和s=1!+2!+3!+4!
时间: 2023-11-24 10:51:54 浏览: 82
以下是两种C语言求和s=1!+2!+3!+4!的例子:
1.方法1:
```c
int main() {
int sum = 0;
for (int i = 1; i <= 4; i++) {
int ret = 1;
for (int j = 1; j <= i; j++) {
ret = j * ret;
}
sum = ret + sum;
}
printf("%d", sum);
system("pause");
return 0;
}
```
2.方法2:
```c
int main() {
int ret = 1;
int sum = 0;
for (int i = 1; i <= 4; i++) {
ret = i * ret;
sum = sum + ret;
}
printf("%d", sum);
system("pause");
return 0;
}
```
相关问题
利用c语言求和s=1!+3!+5!
以下是利用c语言求和s=1! 3! 5!的代码:
```c
#include <stdio.h>
int main()
{
int i, j, s = 0;
for(i = 1; i <= 5; i += 2)
{
int fact = 1;
for(j = 1; j <= i; j++)
{
fact *= j;
}
s += fact;
}
printf("s = %d", s);
return 0;
}
```
在上面的代码中,我们使用了两个for循环。外部的for循环用于循环1、3、5这三个数,内部的for循环用于计算这些数的阶乘。每次计算完阶乘后,将其加到s中。最终,输出s的值即可。
注意,由于1的阶乘为1,因此在计算1的阶乘时,内部的for循环不会执行,从而不会将1加到s中。
求和s=1!+2!+3!
以下是两种C语言求和的例子:
1.仅用for循环
```c
#include<stdio.h>
int main() {
int sum=0,n;
int a=1,i;
printf("请输入n的值:");
scanf("%d",&n);
for(i=1;i<=n;i++) {
a=a*i;
sum=sum+a;
}
printf("%d\n",sum);
}
```
2.分部
```c
#include<stdio.h>
int main() {
int sum=0,n;
int a=1,i;
printf("请输入n的值:");
scanf("%d",&n);
for(i=1;i<=n;i++) {
a=a*i;
printf("%d\n",a); /*显示各个阶乘的具体数值*/
sum=sum+a;
}
printf("结果为:%d\n",sum);
}
```
相关推荐
![](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)