C++ primer plus第六章编程练习答案

1.编写一个程序,读取键盘输入,直到遇到@符号为止,并回显输入(数字除外),同时将大写字符转换为小写,将小写字符转换为大写(别忘了cctype 函数系列)。

#include <iostream>
#include <cctype>
using namespace std;

int main()
{
    char ch;

    cout << "Type, and I shall repeat(@ to quit)." << endl;
    while (cin.get(ch) && ch != '@')
    {
        if (islower(ch))
        {
            ch = toupper(ch);
        }
        else if (isupper(ch))
        {
            ch = tolower(ch);
        }
        if (!isdigit(ch))
        {
            cout.put(ch);
        }
    }
    cout << "\nPlease excuse the slight confusion." << endl;

    return 0;
}

2.编写一个程序,最多将 10个 donation 值读入到一个 double 数组中(如果您愿意,也可使用模板类 arTay)程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。

#include <iostream>
#include <array>
using namespace std;

int main()
{
    int i = 0, j = 0;
    unsigned int count = 0;
    const int ArSize = 10;
    array<double, ArSize> donations;
    double total = 0.0, average = 0.0;

    cout << "You may enter up to " << ArSize;
    cout << " donation (q to terminate)." << endl;
    cout << "donation #1: ";
    while (i < ArSize && cin >> donations[i])
    {
        if (++i < ArSize)
        {
            cout << "donation #" << i + 1 << ": ";
        }
    }

    for (j = 0; j < i; j++)
    {
        total += donations[j];
    }
    average = total / i;
    for (j = 0; j < i; j++)
    {
        if (average < donations[j])
        {
            ++count;
        }
    }

    if (0 == i)
    {
        cout << "No donation!" << endl;
    }
    else
    {
        cout << average << " = average of ";
        cout << i << " donations.\n";
        cout << count << " numbers are greater than the average." << endl;
    }

    return 0;
}

3.编写一个菜单动程序的雏形该程序显示一个提供4个选项的菜单一-每个选项用一个字母标记如果用户使用有效选项之外的字母进行响应,程序将提示用户输入一个有效的字母,直到用户这样做为止。然后,该程序使用一条 switch 语句,根据用户的选择扳行一个简单操作。该程序的运行情况如下:
Please enter one of the- following choices:
c] carnivore
p) pianist
t] tree
g) game
Please enter a c.P,t,or g: qPlease enter a c,p,t, or g: t
A mapleisa tree.

#include <iostream>
using namespace std;

void show_menu();

int main()
{
    char ch;

    show_menu();
    while (cin >> ch)
    {
        switch (ch)
        {
            case 'c':
            {
                cout << "Pandas are also carnivores." << endl;
                break;
            }
            case 'p':
            {
                cout << "Mozart is an excellent pianist." << endl;
                break;
            }
            case 't':
            {
                cout << "A maple is a tree." << endl;
                break;
            }
            case 'g':
            {
                cout << "Playing game can relax yourself." << endl;
                break;
            }
            default:
            {
                cout << "Please enter a c, p, t, or g: ";
                break;
            }
        }
        if ('c' == ch || 'p' == ch || 't' == ch || 'g' == ch)
        {
            break;
        }
    }

    return 0;
}

void show_menu()
{
    cout << "Please enter one of the following choices:" << endl;
    cout << "c) carnivore           p) pianist" << endl;
    cout << "t) tree                g) game" << endl;
}

4.加 Benevolent Order of Programmer 后,在 BOP 大会上人们便可以通过加入者的真实姓名、失衔或秘密 BOP 姓名来了解他《她)。请编写一个程序,可以使用真实姓名、头衔、秘密姓名或成员偏好来列出成员。编写该程序时,请使用下面的结构:
// BenevolentOrder of Programmers name structure
structbop
char fullname[strsize]; // real name
char titlestrsize];
// job title
char bopname strsizel;  // secret BOp name
int preference;
// 0-fullname,1= title,2 = bopname
该程序创建一个由上述结构组成的小型数组,并将其初始化为适当的值。另外,该程序使用一个循环,让用户在下面的选项中进行选择:
a. display by nameb. display by title
c display by bopname d. display by preference
q.qyit
注意,“display by preference”并不意味着显示成员的偏好,而是意味着根据成员的偏好来列出成员。例如,如果偏好号为1,则选择 d 将显示程序员的头衔,该程序的运行情况如下
Benevolent Order of Prog;ammers Report
a.display by nameb. display by title
c.display by bopname d. display by preference
g.guitEnter your choice: a
Wimp Macho
Raki Rhodes
Celia LaiterHoppy Hipman
Pat Hand
Next choice: d
Wimp Macho
Junior Programmer
MIPS
Analyst Trainee
LOOPY
Next choice: q
Bye!

#include <iostream>
using namespace std;

const int NUM = 5;
const int strsize = 20;

struct bop
{
    char fullname[strsize];
    char title[strsize];
    char bopname[strsize];
    int preference;
};

void show_menu();

int main()
{
    char ch;
    bop people[NUM] = 
    {
        {"Wimp Macho", "Teacher", "WMA", 0},
        {"Raki Rhodes", "Junior Programmer", "RHES", 1},
        {"Celia Laiter", "Professor", "MIPS", 2},
        {"Hoppy Hipman", "Analyst Trainee", "HPAN", 1},
        {"Pat Hand", "Animal Keeper", "LOOPY", 2}
    };

    show_menu();
    cout << "Enter your choice: ";
    while (cin >> ch && ch != 'q')
    {
        switch (ch)
        {
            case 'a':
            {
                for (int i = 0; i < NUM; i++)
                {
                    cout << people[i].fullname << endl;
                }
                break;
            }
            case 'b':
            {
                for (int i = 0; i < NUM; i++)
                {
                    cout << people[i].title << endl;
                }
                break;
            }
            case 'c':
            {
                for (int i = 0; i < NUM; i++)
                {
                    cout << people[i].bopname << endl;
                }
                break;
            }
            case 'd':
            {
                for (int i = 0; i < NUM; i++)
                {
                    switch (people[i].preference)
                    {
                        case 0:
                        {
                            cout << people[i].fullname << endl;
                            break;
                        }
                        case 1:
                        {
                            cout << people[i].title << endl;
                            break;
                        }
                        case 2:
                        {
                            cout << people[i].bopname << endl;
                            break;
                        }
                    }
                }
                break;
            }
            default:
            {
                cout << "Illegal input!" << endl;
                break;
            }
        }
        cout << "Next choice: ";
    }
    cout << "Bye!" << endl;

    return 0;
}

void show_menu()
{
    cout << "Benevolent Order of Programmers Report" << endl;
    cout << "a. display by name     b. display by title" << endl;
    cout << "c. display by bopname  d. display by preference" << endl;
    cout << "q. quit" << endl;
}

5.在Ncutronia王国,货币单位是tvarp,收入所得税的计算方式如下5000 tvarps:不收税
5001-15000 tvarps: 10%
15001~35000 tvarps: 15%
35000 tvarps 以上:20%
例如,收入为 38000 tvarps 时,所得税为 5000 x 0.00 + 10000 x .10 + 20000 x 0.5 + 3000 x 0.20,即4600 tvarps。请编写一个程序,使用循环来要求用户输入收入,并报告所得税。当用户输入负数或非数字时,循环将结束。

#include <iostream>
using namespace std;

int main()
{
    const double TVARPS_5000 = 0.0;
    const double TVARPS_5000_15000 = 0.1;
    const double TVARPS_15001_35000 = 0.15;
    const double TVARPS_35000 = 0.2;
    double wage, tax;

    cout << "Please enter your wage (q or <0 to quit): ";
    while (cin >> wage && wage > 0)
    {
        cout << "Your wage: " << wage << " tvarps.\n";
        if (wage < 5000)
        {
            tax = 0.0;
        }
        else if (wage < 15000)
        {
            tax = (wage - 5000) * TVARPS_5000_15000;
        }
        else if (wage < 35000)
        {
            tax = (wage - 15000) * TVARPS_15001_35000 + 10000 * TVARPS_5000_15000;
        }
        else
        {
            tax = (wage - 35000) * TVARPS_35000 + 20000 * TVARPS_15001_35000 + 10000 * TVARPS_5000_15000;
        }
        cout << "Your tax: " << tax << " tvarps.\n";
        cout << "Next wage (q or <0 to quit): ";
    }
    cout << "Bye." << endl;

    return 0;
}

6.编写一个程序,记录抬助给“维护合法权利团体”的资金。该程序要求用户输入捐献者数目,然后要求用户输入每一个拐献者的姓名和款项。这些信息被储存在一个动态分配的结构数组中,每个结构有两个成员:用来储存姓名的字符数组 (或 string 对象) 和用来存储款项的 double 成员。读取所有的数据后,程序将显示所有捐款超过 10000 的报款者的姓名及其报款数额。该列表前应包含一个标题,指出下面的打款者是重要捐款人(Grand Patrons)。然后,程序将列出其他的捐款者,该列表要以 Patrons 开头。如果某种类别没有捐款者,则程序将打印单词“none”。该程序只显示这两种类别,而不进行排序。

#include <iostream>
#include <string>
using namespace std;

const int HIGH_MONEY = 10000;

struct corporation
{
    string name;
    double money;
};

int main()
{
    int i, num;
    unsigned int patrons = 0;
    unsigned int grand_patrons = 0;

    cout << "Please enter the number of donators: ";
    (cin >> num).get(); //吸收换行符;
    corporation *people = new corporation[num];

    for (i = 0; i < num; i++)
    {
        cout << "Please enter name #" << i + 1 << ": ";
        getline(cin, people[i].name);
        cout << "Please enter the amount of donation #" << i + 1 << ": ";
        while (!(cin >> people[i].money)) //处理错误输入;
        {
            cin.clear();
            while (cin.get() != '\n')
                continue;
            cout << "Please enter a number: ";
        }
        cin.get(); //吸收正确输入时的换行符;
    }
    for (i = 0; i < num; i++)
    {
        HIGH_MONEY < people[i].money ? ++grand_patrons : ++patrons; //条件运算符代替条件语句;
    }

    cout << "\nGrand Patrons:" << endl;
    if (grand_patrons != 0)
    {
        for (i = 0; i < num; i++)
        {
            if (people[i].money > HIGH_MONEY)
            {
                cout << "Name: " << people[i].name;
                cout << "\nMoney: " << people[i].money << endl;
            }
        }
    }
    else
    {
        cout << "none" << endl;
    }

    cout << "\nPatrons:" << endl;
    if (patrons != 0)
    {
        for (i = 0; i < num; i++)
        {
            if (people[i].money < HIGH_MONEY)
            {
                cout << "Name: " << people[i].name;
                cout << "\nMoney: " << people[i].money << endl;
            }
        }
    }
    else
    {
        cout << "none" << endl;
    }
    delete[] people;

    return 0;
}

7.编写一个程序,它每次读取一个单词,直到用户只输入q。然后,该程序指出有多少个单词以元音打头,有多少个单词以辅音打头,还有多少个单词不属于这两类。为此,方法之一是,使用 isalpha( )来区分以字母和其他字符打头的单词,然后对于通过了 isapha()测试的单词,使用或 switch 语来确定哪些以元音打头。该程序的运行情况如下:
Enter words (q to quit):
The 12 awesome oxen ambled
quietly across 15 meters of lawn.q
5 worda beginning with vowels
4 worda beginning with consonants
2 others

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main()
{
    string words;
    unsigned int vowels = 0;
    unsigned int consonants = 0;
    unsigned int others = 0;

    cout << "Enter words (q to quit):" << endl;
    while (cin >> words, words != "q")
    {
        if (isalpha(words[0]))
        {
            switch (tolower(words[0]))
            {
                case 'a':
                case 'e':
                case 'i':
                case 'o':
                case 'u':
                {
                    ++vowels;
                    break;
                }
                default:
                {
                    ++consonants;
                    break;
                }
            }
        }
        else
        {
            ++others;
        }
    }
    cout << vowels << " words beginning with vowels" << endl;
    cout << consonants << " words beginning with consonants" << endl;
    cout << others << " others" << endl;

    return 0;
}

8.编写一个程序,它打开一个文件文件,逐个字符地读取该文件,直到到达文件末尾,然后指出该文件中包含多少个字符。

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

int main()
{
    char ch;
    ifstream infile;
    string filename;
    unsigned int count = 0;

    cout << "Please enter name of data file: ";
    getline(cin, filename);
    infile.open(filename);

    if (!infile.is_open())
    {
        cout << "Could not open the file " << filename << endl;
        cout << "Program terminating." << endl;
        exit(EXIT_FAILURE);
    }
    while (infile.get(ch), infile.good())
    {
        ++count;
        cout.put(ch);
    }
    if (0 == count)
    {
        cout << "No data processed." << endl;
    }
    else
    {
        cout << count << " characters in the file " << filename << endl;
    }
    infile.close();

    return 0;
}

9.完成编程练习 6,但从文件中读取所需的信息。该文件的第一项应为捐款人数,余下的内容应为成对的行。在每一对中,第一行为捐款人姓名,第二行为捐款数额。即该文件类似于下面:
Sam Stone
2000
Freida rlass
100500
Tammy Tubbs
5000
Rich Raptor
55000

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

const int HIGH_MONEY = 10000;

struct corporation
{
    string name;
    double money;
};

int main()
{
    int i, num;
    string filename;
    ifstream infile;
    unsigned int patrons = 0;
    unsigned int grand_patrons = 0;

    cout << "Please enter name of data file: ";
    getline(cin, filename);
    infile.open(filename);
    if (!infile.is_open())
    {
        cout << "Could not open the file " << filename << endl;
        cout << "Program terminating." << endl;
        exit(EXIT_FAILURE);
    }

    (infile >> num).get();
    corporation *people = new corporation[num];
    for (i = 0; i < num && infile.good(); i++)
    {
        getline(infile, people[i].name);
        while (!(infile >> people[i].money)) //处理错误输入;
        {
            infile.clear();
            while (infile.get() != '\n')
                continue;
        }
        while (infile.get() != '\n')
            continue;
    }
    infile.close();

    for (i = 0; i < num; i++)
    {
        HIGH_MONEY < people[i].money ? ++grand_patrons : ++patrons; //条件运算符代替条件语句;
    }

    cout << "\nGrand Patrons:" << endl;
    if (grand_patrons != 0)
    {
        for (i = 0; i < num; i++)
        {
            if (people[i].money > HIGH_MONEY)
            {
                cout << "Name: " << people[i].name;
                cout << "\nMoney: " << people[i].money << endl;
            }
        }
    }
    else
    {
        cout << "none" << endl;
    }

    cout << "\nPatrons:" << endl;
    if (patrons != 0)
    {
        for (i = 0; i < num; i++)
        {
            if (people[i].money < HIGH_MONEY)
            {
                cout << "Name: " << people[i].name;
                cout << "\nMoney: " << people[i].money << endl;
            }
        }
    }
    else
    {
        cout << "none" << endl;
    }
    delete[] people;

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值