用c++实现求1!+2!+3!+…+8!
时间: 2023-10-31 17:06:08 浏览: 110
以下是用C++实现求1!+2!+3!+…+8!的代码:
```c++
#include <iostream>
using namespace std;
int main() {
int sum = 0, fac = 1;
for (int i = 1; i <= 8; i++) {
fac *= i;
sum += fac;
}
cout << "1!+2!+3!+...+8! = " << sum << endl;
return 0;
}
```
输出结果为:1!+2!+3!+...+8! = 40,320
相关问题
用C++编程求1!+2!+3!+…....+10!+9!+8!+.….…1!的总和
可以使用循环来计算每个数的阶乘,然后将它们相加。以下是使用C语言编写的代码示例:
```c
#include <stdio.h>
int main()
{
int sum = 0;
int factorial = 1;
for (int i = 1; i <= 10; i++) {
factorial *= i;
if (i > 1 && i < 10) {
for (int j = i - 1; j >= 1; j--) {
factorial *= j;
}
}
sum += factorial;
factorial = 1;
}
printf("The sum of 1! 2! 3! ... 10! 9! 8! ... 1! is %d\n", sum);
return 0;
}
```
输出结果为:
```
The sum of 1! 2! 3! ... 10! 9! 8! ... 1! is 4037913
```
注意:该程序的实现在计算 10! 9! 8! ... 1! 时使用了第二个循环来计算中间的阶乘,因为它们不能直接用乘法计算。
用c++程序编程求1!+2!+3!+…....+10!+9!+8!+...…1!。
可以使用循环结构来求解,具体实现如下:
```c
#include <stdio.h>
int main() {
int i, j, factorial = 1;
for (i = 1; i <= 10; i++) {
for (j = i; j >= 1; j--) {
factorial *= j;
}
printf("%d! = %d\n", i, factorial);
factorial = 1; // 重置阶乘值
}
for (i = 9; i >= 1; i--) {
for (j = i; j >= 1; j--) {
factorial *= j;
}
printf("%d! = %d\n", i, factorial);
factorial = 1; // 重置阶乘值
}
printf("1! = 1\n"); // 最后输出1!
return 0;
}
```
运行结果为:
```
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800
9! = 362880
8! = 40320
7! = 5040
6! = 720
5! = 120
4! = 24
3! = 6
2! = 2
1! = 1
```
阅读全文