Accelerated C++ Exercises Ch3

3-2

Write a program to compute and print the quartiles (that is, the quarter of the numbers with the largest values, the next highest quarter, and so on) of a set of integers.

#include <iostream>
#include <ios>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <functional>//std::greater<double>

using std::cin;
using std::cout;
using std::endl;
using std::vector;
using std::sort;
using std::streamsize;
using std::setprecision;

int main()
{
    double x;
    vector<double>numbers;
    cout << "input x1:";
    while (cin >> x)
    {
        numbers.push_back(x);
        cout << "input x" << numbers.size()+1 << ':';
    }
    typedef vector<double>::size_type vec_sz;
    vec_sz size = numbers.size();
    if (size % 4 != 0)
    {
        cout << "cannot distribute to 4 piles!" << endl;
        return 1;
    }
    sort(numbers.begin(), numbers.end(), std::greater<double>());
    streamsize prec = cout.precision();
    setprecision(3);
    size_t j = 0;
    for (size_t i = 0; i < 4; i++)
    {
        for (; j < (i+1) * size / 4; j++)
            cout << numbers[j] << '\t';
        cout << endl;
    }
    setprecision(prec);
    system("pause");
    return 0;
}

3-3

Write a program to count how many times each distinct word appears in its input.

#include <iostream>
#include <string>
#include <vector>
#include <ios>
#include <iomanip>

using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::string;

int main()
{
    vector<string>words;
    vector<int>counts;
    string str;
    typedef vector<string>::size_type words_sz;
    typedef vector<int>::size_type counts_sz;
    cout << "input words:";
    while (cin>>str)
    {
        int flag = 0;
        for (words_sz i = 0; i != words.size(); i++)
            if (str == words[i])
            {
                flag = 1;
                counts[i]++;
            }
        if (flag == 0)
        {
            words.push_back(str);
            counts.push_back(1);
        }
    }
    counts_sz j = 0;
    for (words_sz i = 0; i != words.size(); i++)
    {
        cout << words[i] << ":\t" << counts[j++] << endl;
    }
    system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值