C++:vector头尾数字相加

题目

  1. 将所有数据读入到vector;
  2. 使用循环对数字进行添加,并且输出.
  3. 当数字为奇数时,输出没有被加的那个数字.

分析

  1. 第一个简单.
  2. 第二个需要做的是,让首尾相加,不能多加,也不能少加.因此可以判断是否循环已经到了整个vector的数字的一半.
  3. 另外一个比较复杂的问题是:当整个vector的总数是奇数时,中间的那个数字就没有可以加的数字了,就直接输出就行.

C++.
image-1977

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*************************************************************************
    > File Name: test.3.13.1.cpp
    > Author: puruidong
    > Mail: 1@w1520.com
    > Created Time: 2013年12月21日 星期六 22时40分05秒
 ************************************************************************/

#include<iostream>
#include<vector>
using namespace std;
int main()
{
    int var ;
    vector<int> ivec;
    cout << "input number?" << endl;
    while(cin >> var ){
        ivec.push_back(var);
    }
    for (vector<int>::size_type index=0;index<(ivec.size()+1)/2;++index){//前后相加.
        if(index!=ivec.size()/2){  
        cout <<
        "\njieguo?\n" <<
         ivec[index] + ivec[ivec.size()-(index+1)] << endl;
        }else{
        cout << "is one number :" <<
        ivec[ivec.size()/2] << endl;
        }
    }

    return 0;
}

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

*

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据