Accelerated C++ Exercises Ch3

来源:互联网 发布:环绕音乐软件 编辑:程序博客网 时间:2024/05/23 00:00

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");}
0 0
原创粉丝点击