C++ primer 第五版 练习3.20 答案

该博客提供了一个C++代码示例,用于解决当输入向量长度为奇数时,如何使其变为偶数长度并计算相邻元素及首尾配对元素之和的问题。代码中首先读取用户输入的整数,然后检查向量长度是否为奇数,如果是,则要求用户输入额外的数字。接着,代码分别输出了相邻元素的和以及首尾配对元素的和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<string>
#include<vector>
using std::vector;
using std::string;
using std::cout;
using std::endl;
using std::cin;

int main()
{
    vector<int> a;
    int num = 0;
    while (cin >> num)
        a.push_back(num);
    cout << a.size() << endl;
    cin.clear();    //重置输入流,这里非常重要
    while (a.size() % 2 != 0)
    {
        cout << "the number of the vector is odd, please add a more number" << endl;
        cin >> num;
        a.push_back(num);
    }
    for (auto temp : a)
    {
        cout << temp << " ";
    }
    cout << endl;
    //print the sum of pair of adjacent elements
    vector<int>::iterator it,it1,it2;
    for (it = a.begin(); it != a.end(); it++)
    {
        int num1 = *it;
        it++;
        num1 += *it;
        cout << num1 << " ";
    }
    cout << endl;

    //print the sum of first and last elements,followed by the sum of the second and second-to-last,and so on
    int count = 0;
    for (it = a.begin(); it != a.begin() + a.size() / 2; it++)
    {
        int num2 = *it;
        num2 += *(a.end() - 1 - count);
        cout << num2 << " ";
        count++;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值