c语言分别用迭代法和递归法编写一个求n!的函数 来求1!+2!+3!+…+10!的值
时间: 2023-09-07 10:15:00 浏览: 91
迭代法实现n!的函数:
```c
#include <stdio.h>
int factorial_iterative(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += factorial_iterative(i);
}
printf("1!+2!+3!+...+10!=%d\n", sum);
return 0;
}
```
递归法实现n!的函数:
```c
#include <stdio.h>
int factorial_recursive(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial_recursive(n - 1);
}
}
int main() {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += factorial_recursive(i);
}
printf("1!+2!+3!+...+10!=%d\n", sum);
return 0;
}
```
阅读全文