用c++写一个求n项和的代码
以下是用C++编写的求前n项和的代码:
#include
int main() { int n, sum = 0; cout << "请输入n的值:"; cin >> n; for (int i = 1; i <= n; i++) { sum += i; } cout << "前" << n << "项和为:" << sum << endl; return 0; }
其中,n为输入的项数,sum为累加和的变量,for循环用于计算累加和,最后输出结果。
原文地址: http://www.cveoy.top/t/topic/bd8A 著作权归作者所有。请勿转载和采集!