C语言用while循环求1!+2+!+3!+4!+5!+6!)
时间: 2023-11-24 13:51:26 浏览: 79
以下是使用while循环求1!+2!+3!+4!+5!+6!的C语言代码:
```c
#include <stdio.h>
int main() {
int i = 1, j = 1, sum = 0;
while (i <= 6) {
j = 1;
int temp = 1;
while (j <= i) {
temp *= j;
j++;
}
sum += temp;
i++;
}
printf("1!+2!+3!+4!+5!+6!=%d", sum);
return 0;
}
```
相关问题
c语言求1!+2!+3!+4!+5!代码加运行结果用while和for循环写
以下是使用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;
}
```
用c语言求 1!+2!+3!+4!+5!+…+15!
可以使用for循环或者while循环来实现1!+2!+3!+4!+5!+…+15!的累加。具体代码如下:
方法一:使用for循环
```c
#include <stdio.h>
int main()
{
int i, n;
long long sum = 0, factorial = 1;
printf("请输入N的值:");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
factorial *= i;
sum += factorial;
}
printf("1!+2!+3!+...+%d! = %lld\n", n, sum);
return 0;
}
```
方法二:使用while循环
```c
#include <stdio.h>
int main()
{
int i = 1, n;
long long sum = 0, factorial = 1;
printf("请输入N的值:");
scanf("%d", &n);
while (i <= n) {
factorial *= i;
sum += factorial;
i++;
}
printf("1!+2!+3!+...+%d! = %lld\n", n, sum);
return 0;
}
```
阅读全文