//然后修改程序:头尾元素两两配对(第一个和最后一个,第二个和倒数第二个,以此类推),计算每对元素的和,并输出。
//读一组整数到vector 对象,计算并输出每对相邻元素的和
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> ivec;
int ival;
//读入数据到vector对象
cout<<"Enter numbers(Ctrl+Z to end): "<<endl;
while (cin>>ival)
{
ivec.push_back(ival);
}
if (ivec.size() == 0)
{
cout<<"No elements?!"<<endl;return -1;
}
//计算相邻的元素的和并输出
cout << "Sum of each pair of adjacent elements in the vector: "<< endl;
for (vector<int>::size_type ix = 0; ix<ivec.size()-1; ix=ix+2)
{
cout<<ivec[ix]+ivec[ix+1]<<"\t";if ((ix+2) % 12 == 0) //每行输出6个和{
cout<<endl;
}
}
//提示最后一个元素没有求和
if (ivec.size()%2 != 0)
{
cout << endl<< "The last element is not been summed "<< "and its value is "<< ivec[ivec.size()-1] << endl;
}}
return 0;
//读一组整数到vector 对象,计算首尾配对元素的和并输出
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> ivec;
int ival;
//读入数据到vector对象
cout<<"Enter numbers(Ctrl+Z to end): "<<endl;
while (cin>>ival)
{
ivec.push_back(ival);
}
if (ivec.size() == 0)
{
cout<<"No elements?!"<<endl;
return -1;
}
//计算相邻的元素的和并输出
cout << "Sum of each pair of counterpart elements in the vector: "<< endl;
vector<int>::size_type num = 0;
for (vector<int>::size_type first = 0, last = ivec.size()-1; first<last; ++first,--last)
{
cout<<ivec[first]+ivec[last]<<"\t";
++num;
if (num % 6 == 0) //每行输出6个和
{
cout<<endl;
}
}
//提示居中元素没有求和
if (ivec.size()%2 != 0)
{
cout << endl
<< "The center element is not been summed "
<< "and its value is "
<< ivec[(ivec.size()-1)/2] << endl;
}}
return 0;