用C语言求 1!+2!+3!+4!+5!+…+15
时间: 2023-12-30 14:04:06 浏览: 109
以下是两种用C语言求解1!+2!+3!+4!+5!+…+15的代码示例:
1. 使用固定循环次数的代码:
```c
#include <stdio.h>
int main() {
int i, n = 15;
int set = 1;
int sum = 0;
for (i = 1; i <= n; i++) {
set = set * i;
sum = sum + set;
}
printf("%d\n", sum);
return 0;
}
```
2. 使用用户输入的循环次数的代码:
```c
#include <stdio.h>
int main() {
int i, n;
int set = 1;
int sum = 0;
printf("请输入一个整数n:");
scanf("%d", &n);
for (i = 1; i <= n; i++) {
set = set * i;
sum = sum + set;
}
printf("%d\n", sum);
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;
}
```
C语言求 1!+2!+3!+4!+5!+…+15
这个问题可以通过使用循环和递归两种方法来解决。下面是两种方法的代码实现:
方法一:使用循环
```c
#include <stdio.h>
int main() {
int n = 15;
int sum = 0;
int factorial = 1;
for (int i = 1; i <= n; i++) {
factorial *= i;
sum += factorial;
}
printf("1!+2!+3!+...+15! = %d\n", sum);
return 0;
}
```
方法二:使用递归
```c
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int n = 15;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial(i);
}
printf("1!+2!+3!+...+15! = %d\n", sum);
return 0;
}
```
阅读全文