计算条款总和的程序?c++
Program to calculate the sum of terms? c++
因此,我试图编写一个程序来计算项的总和,但每个项都是前一项减去前一项的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
(,同时更新last
和last2
变量以保持术语列表的运行。然后在循环外,我将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
}
它使用递归来调用自己,这是可视化此类问题需要做什么的好方法。该函数按原样运行,但仅适用于较小的num
s,否则会出现堆栈溢出。它也相当耗时,因为它要多次执行函数调用和计算所有项。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- C++,系统无法执行指定的程序
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到
- 重载操作程序时出错>>用于类中的字符串 memebr
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 试图在visual studio上用C++创建一个桌面应用程序
- 模板元程序查找相似的连续类型名称
- FFmpeg:制作一个应用程序比直接使用ffmepg更好吗
- 如何通过cpp程序运行shell脚本
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- IPC使用多个管道和分支进程来运行Python程序
- 如何将c++程序的一些输出传递给shell,以便在shell中使用
- 使用C++程序合并排序没有得到正确的输出
- 基于boost的程序的静态链接——zlib问题
- 程序崩溃并显示"std::out_of_range"错误
- 在C应用程序中运行C++(带有STL)函数
- 使用mongocxx驱动程序时包含头文件问题
- 如何在c++程序中找到函数的地址