c++求1!+2!+3!+...n!
作者:野牛程序员:2024-10-08 18:08:53 C++阅读 2503
c++求1!+2!+3!+...n!
可以通过循环计算每个阶乘并累加。以下是一个简单的C++代码示例:
#include <iostream> unsigned long long factorial(int n) { unsigned long long result = 1; for (int i = 1; i <= n; ++i) { result *= i; } return result; } unsigned long long sumFactorials(int n) { unsigned long long sum = 0; for (int i = 1; i <= n; ++i) { sum += factorial(i); } return sum; } int main() { int n; std::cout << "Enter n: "; std::cin >> n; std::cout << "Sum of factorials: " << sumFactorials(n) << std::endl; return 0; }
运行后输入n
,可以得到1! + 2! + ... + n!的结果。
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
- 上一篇:学c++之前要学c语言吗
- 下一篇:count(1)与count(*)区别