求1+2!+3!+ …… +n!的c++代码
时间: 2023-06-02 20:08:22 浏览: 130
以下是求1~n的阶乘的C代码:
```
#include <stdio.h>
int main() {
int n, i;
long long fact = 1;
printf("请输入一个正整数:");
scanf("%d", &n);
if (n < 0) {
printf("错误:请不要输入负数!\n");
return 1;
}
for (i = 1; i <= n; ++i) {
fact *= i; // 计算阶乘
}
printf("%d 的阶乘是 %lld \n", n, fact);
return 0;
}
```
相关问题
C++求1!+2!+3!+4!+5!……+n!
C++代码如下所示:
```
#include <iostream>
using namespace std;
int main() {
int n, sum = 0, fac = 1;
cout << "请输入n:";
cin >> n;
for (int i = 1; i <= n; i++) {
fac *= i;
sum += fac;
}
cout << "结果是:" << sum << endl;
return 0;
}
```
求1+2!+3!+ …… +n!的C/C++程序代码:
可以使用循环结构来求解1+2!+3!+...+n!的和。以下是一个C++的程序代码示例:
```cpp
#include <iostream>
using namespace std;
int factorial(int num) {
int result = 1;
for (int i = 1; i <= num; i++) {
result *= i;
}
return result;
}
int main() {
int n;
cout << "请输入一个正整数n:";
cin >> n;
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += factorial(i);
}
cout << "1+2!+3!+...+n!的和为:" << sum << endl;
return 0;
}
```
阅读全文