C++程序计算前n个自然数的立方和
给定一个整数n,任务是找到前n个自然数的立方和。所以,我们必须将n个自然数立方并求和。
对于每个n,结果应该是1^3 + 2^3 + 3^3 + … + n^3。例如,n = 4,则上述问题的结果应该是:1^3 + 2^3 + 3^3 + 4^3。
输入
4
输出
100
解释
1^3 + 2^3 + 3^3 + 4^3 = 100.
输入
8
输出
1296
解释
1^3 + 2^3 + 3^3 + 4^3 + 5^3 + 6^3 + 7^3 +8^3 = 1296.
下面使用的解决问题的方法如下
我们将使用简单的迭代方法,其中可以使用任何循环,例如-for循环、while循环、do-while循环。
从1迭代到n。
对于每个i,求其立方。
将所有立方体加到一个sum变量中。
返回sum变量。
打印结果。
算法
Start Step 1→ declare function to calculate cube of first n natural numbers int series_sum(int total) declare int sum = 0 Loop For int i = 1 and i <= total and i++ Set sum += i * i * i End return sum step 2→ In main() declare int total = 10 series_sum(total) Stop
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
#include <iostream> using namespace std; //function to calculate the sum of series int series_sum(int total){ int sum = 0; for (int i = 1; i <= total; i++) sum += i * i * i; return sum; } int main(){ int total = 10; cout<<"sum of series is : "<<series_sum(total); return 0; }
输出
如果运行以上代码,它将生成以下输出:
sum of series is : 3025
广告