读一组整数到vector对象,计算并输出每对相邻元素的和。如果读入元素个数为奇数,则提示用户最后一个元素没有求和,并输出其值。
看到这题我写的代码:
/*********** my code **************/
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int val;
vector<int> num_vec;
int num_cnt = 0;
while(cin >> val)
{
num_vec.push_back(val);
++num_cnt;
if( (num_cnt != 0) && (num_cnt % 2 == 0) )
cout << num_vec[num_cnt - 1] + num_vec[num_cnt - 2] << endl;
}
if(num_cnt % 2 != 0)
cout << "The number of integers you entered is odd, so the last integer "
<< num_vec[num_cnt - 1] << " is not calculated" << endl;
system("pause");
return 0;
}
习题解答里给出的参考代码:
/*********** better code in reference book **************/
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> num_ivec;
int ival;
cout << "enter numbers(Ctrl+Z to end):" << endl;
while(cin >> ival)
num_ivec.push_back(ival);
if(num_ivec.size() == 0){
cout << "No element?!" << endl;
return -1;
}
cout << "Sum of each pair of adjacent elements in the vector:" << endl;
for(vector<int>::size_type ix = 0; ix < num_ivec.size()-1; ix += 2){
cout << num_ivec[ix] + num_ivec[ix+1] << "\t";
if( (ix+1) % 6 == 0 )
cout << endl;
}
if(num_ivec.size() % 2 != 0)
cout << endl
<< "The last element is not been summed "
<< "and its value is "
<< num_ivec[num_ivec.size()-1] << endl;
system("pause");
return 0;
}
我的程序的问题:
1. 给用户的输入提示不够
2. 程序结构条理不清楚,此为硬伤啊= =!代码应该能够自己解释自己,但是我写的程序就像一幅乱糟糟的线条组成的画一样,虽然也能跑出正确结果,但是不容易让人看出来画的是什么,所以写程序不能一上来就开始敲代码,想到哪里写到哪里,应该先有个思考组织的过程,分清程序先干什么后干什么,就像画画要先构图一样^_^.
3. 程序不利于扩展,按照我写的这段代码,如果要求改成了求头尾元素两两配对之和,怎么办?这当然可以做到,但是大部分代码都得重写!然而在参考代码中,只需要改下for循环的条件还有用于加和的元素下标就可以了,so easy
4. 元素下标等尽量不要使用变量,使用可以计算的固定的值比较好,如迭代器最后一个元素的下标值num_ivec[num_ivec.size()-1],而不使用ix,不然还得想ix此时变到了多少......
自己的代码吐槽完毕,看论文去了~~