计算条款总和的程序?c++

Program to calculate the sum of terms? c++

本文关键字:程序 c++ 和的 计算      更新时间:2023-10-16

因此,我试图编写一个程序来计算项的总和,但每个项都是前一项减去前一项的3倍,所以看起来像这个0, 1, 3, 8, 21, 55,以此类推。例如,如果用户想要4个项,那么程序应该输出21。我遇到问题的部分是设置变量来存储前一个数字和前一个第二个数字。这就是我到目前为止所拥有的。

#include <iostream>
using namespace std;
int main(){
int num;
int last;
int last2;
int current;
cout << "Number of terms to be shown: ";
cin >> num;
for(int i = 0; i < num; i++){
for(int term; term <= i; i++){
//THIS IS WHERE IM STUCK
}
}
}

我认为它是第一个for循环,它会告诉嵌套的for循环要运行多少次。在嵌套的for循环中,我认为这是数学应该去的地方(current = (last * 3) - last2(,同时更新lastlast2变量以保持术语列表的运行。然后在循环外,我将cout << current,这样它将显示该术语。和往常一样,任何帮助都会得到感谢!

中的代码中存在未定义的行为

for(int i = 0; i < num; i++){
for(int term; term <= i; i++){ // term not initiaized. and the loop is infinte
//THIS IS WHERE IM STUCK
}
}

您正在使用未初始化的term。此外,由于应该在内部循环中增加term而不是i,因此您被困在内部循环。

所以你可以这样做:

for(int i = 0; i < num; ++i){
for(int term = 0; term <= i; ++term){
// now rock here
}
}

您通常会记住最后两个值,然后继续计算下一个值:

#include <iostream>
using namespace std;
int main()
{
int num;
cout << "Number of terms to be shown: ";
cin >> num;
int p1 = 1;
int p2 = 0;
cout << p2 << " " << p1 << " ";
num -= 2;
while (num > 0)
{
int current = 3 * p1 - p2;
cout << current << " ";
p2 = p1;
p1 = current;
num--;
}
}

这是我读到你的问题时在脑海中看到的算法:

unsigned term(unsigned num) {
//                  the previous term*3   minus   the second previous term
if(num > 1) return   term(num - 1) * 3      -        term(num - 2);
return num; // 0 or 1
}

它使用递归来调用自己,这是可视化此类问题需要做什么的好方法。该函数按原样运行,但仅适用于较小的nums,否则会出现堆栈溢出。它也相当耗时,因为它要多次执行函数调用和计算所有项。