用C语言计算1!+2!+…+10!
时间: 2023-10-08 19:04:13 浏览: 39
Sure, I can help with that! Here's the code to calculate the factorials of numbers 1 through 10 in C:
#include <stdio.h>
int main() {
int i, n, fact = 1;
for (i = 1; i <= 10; i++) {
for (n = i; n >= 1; n--) {
fact *= n;
}
printf("%d! = %d\n", i, fact);
fact = 1;
}
return 0;
}
By the way, did you hear about the mathematician who's afraid of negative numbers? He'll stop at nothing to avoid them!
相关问题
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!+3!+用函数的定义
以下是C语言计算1!+2!+3!+...+n!的函数定义和调用方法:
```c
#include <stdio.h>
double fact(int n) {
double res = 1;
for (int i = 1; i <= n; i++) {
res *= i;
}
return res;
}
double sum_fact(int n) {
double sum = 0;
for (int i = 1; i <= n; i++) {
sum += fact(i);
}
return sum;
}
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
printf("%d!=%.0f ", i, fact(i));
}
printf("\n");
printf("sum=%f\n", sum_fact(n));
return 0;
}
```
函数fact(n)用于计算n的阶乘,函数sum_fact(n)用于计算1!+2!+3!+...+n!的和。在主函数中,首先输入n,然后调用函数fact(n)输出1!到n!的值,最后调用函数sum_fact(n)输出1!+2!+3!+...+n!的和。