c语言利用求阶乘函数Fact(),编程计算并输出1! + 2! + …+ n!的值。 **输入格式要求:"%u" 提示信息:"Input n(n>0):" **输出格式要求:"sum = %lu\n" 程序运行示例: Input n(n>0):5 sum = 153
时间: 2024-05-08 10:22:10 浏览: 78
以下是代码实现:
```c
#include <stdio.h>
unsigned int Fact(unsigned int n)
{
if(n == 1 || n == 0)
return 1;
else
return n * Fact(n-1);
}
int main()
{
unsigned int n;
printf("Input n(n>0):");
scanf("%u", &n);
unsigned long sum = 0;
for(unsigned int i = 1; i <= n; i++)
{
sum += Fact(i);
}
printf("sum = %lu\n", sum);
return 0;
}
```
运行结果:
```
Input n(n>0):5
sum = 153
```
相关问题
C语言,利用求阶乘函数fact,编程计算并输出1!+2!+...+n!的值
以下是C语言实现计算1!+2!+3!+……+n!的代码,其中利用了求阶乘函数fact(n):
```c
#include <stdio.h>
double fact(int n) {
double res = 1;
for (int i = 1; i <= n; i++) {
res *= i;
}
return res;
}
double fun(int n) {
double res = 0;
for (int i = 1; i <= n; i++) {
res += fact(i);
}
return res;
}
int main() {
int n;
printf("Enter n: ");
scanf("%d", &n);
printf("%.0f\n", fun(n));
return 0;
}
```
C语言利用求阶乘函数Fact(),编程计算并输出1! + 2! + …+ n!的值。 **输入格式要求:"%u" 提示信息:"Input n(n>0):" **输出格式要求:"sum = %lu\n"
好的,以下是用 C 语言编写计算并输出 $1! + 2! + \cdots + n!$ 的代码:
```c
#include <stdio.h>
unsigned int get_input();
unsigned long factorial(unsigned int n);
unsigned long factorial_sum(unsigned int n);
int main() {
unsigned int n = get_input();
unsigned long sum = factorial_sum(n);
printf("sum = %lu\n", sum);
return 0;
}
unsigned int get_input() {
unsigned int n;
printf("Input n(n>0):");
scanf("%u", &n);
return n;
}
unsigned long factorial(unsigned int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
unsigned long factorial_sum(unsigned int n) {
unsigned long sum = 0;
for (unsigned int i = 1; i <= n; i++) {
sum += factorial(i);
}
return sum;
}
```
其中,使用了函数 `get_input()` 获取用户输入的正整数 `n`,使用了函数 `factorial()` 计算阶乘的值,使用了函数 `factorial_sum()` 计算 $1! + 2! + \cdots + n!$ 的值,并在 `main()` 函数中调用并输出结果。
阅读全文