C++ 计算阶乘之和:高效算法实现与示例
"n" 的阶乘记为 "n!",它的定义如下:"n!" = 1 × 2 × ⋯ × "n"。给定一个正整数 "n",请计算并输出 1! + 2! + 3! + ⋯ + "n"!。比如 1! + 2! + 3! = 1 + 2 + 6 = 9。用c++ 实现该算法可以使用循环,首先定义一个变量sum,用于存储计算结果。然后使用一个循环,从1到n,依次计算每个数的阶乘,并加到sum上。最后输出sum的值即可。以下是使用C++实现该算法的示例代码:"cpp\"#include <iostream>\"\"using namespace std;\"\"int main() {\"\" int n;\"\" cout << \"Enter a positive integer: \" ;\"\" cin >> n;\"\" int sum = 0;\"\" int factorial = 1;\"\" for (int i = 1; i <= n; i++) {\"\" factorial *= i;\"\" sum += factorial;\"\" }\"\" cout << \"The sum of factorial from 1 to \" << n << \" is: \" << sum << endl;\"\" return 0;\"\"}\""运行示例:"\"Enter a positive integer: 3\"\"The sum of factorial from 1 to 3 is: 9\""这样就可以计算并输出给定范围内的阶乘之和了。
原文地址: https://www.cveoy.top/t/topic/pXEQ 著作权归作者所有。请勿转载和采集!