Pentagonal数列问题——2.2

问题:练习2.2pentagonal数列的求值公式是P(n)=n(3n-1)/2,借此产生1,5,12,22,35等元素值。试定义一个函数,利用上述公式,将产生的元素放到用户传入的vector中,元素个数由用户指定。请检查元素个数的有效性。接下来编写第二个函数,能够将给定的vector的所有元素一一打印出来。此函数的第二参数接受一个字符串,便是存放在vector内的数列的类型,最后再写一个main()测试上述两个函数。

程序:

#include<vector>
#include<iostream>
#include<string>
using namespace std;
bool penta_elem(vector<int>&vec,int pos);
void display_message(vector<int>&,const string&,ostream &os=cout);

bool penta_elem(vector<int>&vec,int pos)//pentagognal sequence calculation formula
{
    if(pos<=0||pos>800)//check the position
    {
        cout<<"the position is invalid"<<endl;
        return false;       
    }

    for(int ix=1;ix<=pos;++ix)
        vec.push_back(ix*(3*ix-1)/2);                   
    return true;

}

void display_message(vector&vec,const string &title,ostream &os)//output and print’ function
{

cout<<title<<endl;
for(int ix=0;ix<vec.size();++ix)
    cout<<vec[ix]<<" ";
cout<<endl;

}

int main()
{
int pos;
bool more=true;//use for inputing the position continuous
char again;//judge user whether or not to continuous

while(more)
{
cout<<"Please enter a  position:"<<endl;
cin>>pos;

vector<int>vec;
string title="pentagonal sequence";
//ostream &os=cout;

penta_elem(vec,pos);
display_message(vec,title);

 cout<<"do you want to continue?'Y/N'"<<endl;
 cin>>again;
 if(again!='Y'&&again!='y')
     more=false;
}

}

笔记:
1.vector声明可以不写using std::vector.
2.void display_message(vector&,const string&,ostream &os=cout);在声明的时候就应该将ostream &os=cout初始化,在之后就可以不用初始化了。
调用这个函数需要在主函数中写明vectorvec;
string title=”pentagonal sequence”;
3.1>d:\cjj\cjjpractise\cjjpractise\practise2.2_pentagonal_answer.cpp(27): warning C4018: “<”: 有符号/无符号不匹配——————出现这个原因是在容器说明中 被定义为: unsigned int 类型, 而j是int 类型 所以会出现: 有符号/无符号不匹配 警告 ,错误改正 : 定义j为unsigned 类型后就可以了
4,用户不断输入新的位置,不会每次都需要重新运行的方法是:
bool more=true;//use for inputing the position continuous
char again;//judge user whether or not to continuous

while(more)
{
cout<<"Please enter a  position:"<<endl;
cin>>pos;

//function
 cout<<"do you want to continue?'Y/N'"<<endl;
 cin>>again;
 if(again!='Y'&&again!='y')
     more=false;
}

5.调用计算函数的格式
vectorvec;
string title=”pentagonal sequence”;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章