【C++】C++PrimerPlus(第6版)中文版 第6章 分支语句和逻辑运算符 编程练习 参考答案

自己写的答案,并非最佳答案,仅供参考~

第6章 分支语句和逻辑运算符

1.编写一个程序,读取键盘输入,知道遇到@符号为止,并回显输入(数字除外),同时将大写字符转换为小写,将小写字符转换为大写(别忘了cctype函数系列)。
#include <iostream>
#include <cctype>
​
int main()
{
    cout << "Enter your input, type @ to terminate input:\n";
    char ch;
    cin.get(ch);
    while (ch != '@')
    {
    if (islower(ch))
    {
        ch = toupper(ch);
    }
    else if (isupper(ch))
    {
        ch = tolower(ch);
    }
    if (isdigit(ch) == false)
    {
        cout << ch;
    }
    cin.get(ch);
    }
    cout << endl;
    system("pause");
    return 0;
}
2.编写一个程序,最多将10个donation值读入到一个double数组中(如果你愿意,也可以使用模板array)。程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。
#include <iostream>
​
int main()
{
    using std::cout;
    using std::endl;
    using std::cin;
    double donations[10];
    cout << "请输入十个以内的数,非数字退出,本程序将计算他们的平均值和寻找比平均值大的数字:" << endl;
    int donation;
    {
        int i = 0;
        int total = 0;
        for (int donation; i <= 9; i++) {
            cout << i + 1 << "#:" << endl;
            if (cin >> donation) {
                total += donation;
                donations[i] = donation;
            }
            else {
                break;
            }
​
        }
        int average = total / i;
        cout << "平均值:" << average << endl;
        cout << "比平均值大的数" << endl;
        for (int j = i - 1; j >= 0; j--) {
            if (donations[j] > average) {
                cout << donations[j] << endl;
            }
        }
    }
​
}
3.编写一个菜单驱动程序的雏形。该程序显示一个提供4个选项的菜单——每一个选项用一个字母标记。如果用户使用有效选项之外的字母进行响应,程序将提示用户输入一个有效的字母,直到用户这样做为止。然后,该程序使用一条switch语句,根据用户的选择执行一个简单操作。该程序的运行情况如下:

Please enter one of following choices: c) carnivore p) pianist t) tree g) game

Please enter a c, p, t or g: q Please enter a c, p, t or g: t A maple is a tree.

#include <iostream>
​
int main()
{
    using std::cout;
    using std::cin;
    using std::endl;
​
    cout << "Please enter one of the following choices:"
        << endl << "c) carnivore p) pianist" << endl
        << "t) tree g)game" << endl;
    char ch;
    while (cin >> ch)
    {
        switch (ch)
        {
        case 'C':
        case 'c':
            cout << "A maple is a carnivore";
            break;
        case 'P':
        case 'p':
            cout << "A maple is a pianist";
            break;
        case 'T':
        case 't':
            cout << "A maple is a tree";
            break;
        case 'G':
        case 'g':
            cout << "A maple is a game";
            break;
        default:
            cout << "Please enter a c,p,t, or g:";
        }
    }
}
4.加入Benevolent Order of Programmer后,在BOP大会上,人们便可以通过加入者的真实姓名、头衔或秘密BOP姓名来了解他(她)。请编写一个程序,可以使用真是姓名、头衔、秘密姓名或者成员偏好来列出成员。编写该程序时,请使用下面的结构:

struct bop { char fullname[strsize]; char title[strsize]; char bopname[strsize]; int perference; }; 该程序创建一个由上述结构组成的小型数组,并将其初始化为适当的值。另外,该程序使用一个循环,让用户在下面的选项中进行选择: a. display by name b. display by title c. display by bopname d. display by perference q. quit 注意,“display by perference”并不意味着显示成员的偏好,而是意味着根据成员的偏好来列出成员。例如,如果偏好为1,则选择d将显示成员的头衔。该程序的运行情况如下: Benevolent Oeder of Programmers Report a. display by name b. display by title c. display by bopname d. display by perference q. quit Enter your choice: a Wimp Macho Raki Rhodes Celia Laiter Hoppy Hipman Pat Hand Next choice: d Wimp Macho Junior Programmer MIPS Analyst Trainee LOOPY Next choice: q Bye!

#include <iostream>
​
const int strsize = 20;
struct bop
{
    char fullname[strsize];
    char title[strsize];
    char bopname[strsize];
    int preference;// 0 = fullname, 1 = title, 2 = bopnamek
};
​
int main()
{
    using namespace std;
    bop members[5] = {
        {"Wimp Macho","","",0},
        {"Raki Rhodes","Junior Programmer","",1},
        {"Celia laiter","","MIPS",2},
        {"Hoppy Hipman","Analyst Trainee","",1},
        {"Pat Hand","","LOOPY",2}
    };
    char ch;
    cout << "Benevolent Order of Programmers Report" << endl;
    cout << "a. display by name   b.display by title" << endl
        << "c.display by bopname   d.display by preference" << endl
        << "q.quit" << endl;
    cout << "Enter your choice:";
    while (cin >> ch)
    {
        switch (ch)
        {
        case 'A':
        case 'a':
            for (int i = 0; i < 5; i++) {
                cout << members[i].fullname << endl;
            }
            break;
        case 'B':
        case 'b':
            for (int i = 0; i < 5; i++) {
                cout << members[i].title << endl;
            }
            break;
        case 'C':
        case 'c':
            for (int i = 0; i < 5; i++) {
                cout << members[i].bopname << endl;
            }
            break;
        case 'D':
        case 'd':
            for (int i = 0; i < 5; i++) {
                switch (members[i].preference)
                {
                case 0:
                    cout << members[i].fullname << endl;
                    break;
                case 1:
                    cout << members[i].title << endl;
                    break;
                case 2:
                    cout << members[i].bopname << endl;
                    break;
                }
            }
            break;
        case 'Q':
        case 'q':
            cout << "Bye!" << endl;
            return 0;
        default:
            cout << "Please enter a a,b,c,d, or q:" << endl;
            break;
        }
        cout << "Next Choice:";
    }
}
5.在Neutronia王国,货币单位时tvarp,收入所得税的计算方式如下:

5000tvarps: 不收税 5001~15000tvarps: 10% 15001~35000tvarps : 15 % 35000tvarps以上: 20% 例如,收入为38000tvps时,所得税为50000.00+100000.10+200000.15+30000.20,即4600tvarps。请编写一个程序,使用循环来要求用户输入收入,并报告所得税。当用户输入负数或非数字时,循环将结束。

#include <iostream>
​
int main()
{
    using namespace std;
    unsigned int income;
    unsigned int tax;
    cout << "请输入您的收入:";
    while (cin >> income) {
        if (income > 35000) {
            tax = (income - 35000) * 0.2 + 4000;
        }
        else if ((income > 15000) and (income <= 35000))
        {
            tax = (income - 15000) * 0.15 + 1000;
        }
        else if ((income > 5000) and (income <= 15000))
        {
            tax = (income - 5000) * 0.1;
        }
        else
        {
            cout << "无需税收!";
            continue;
        }
        cout << "您的税收为:" << tax << "tvarps";
        cout << endl << "请输入您的收入";
    }
}
6.编写一个程序,记录捐助给“维护合法权利团体”的资金。该程序要求用户输入捐献者的数目,然后要求用户输入每一个捐献者的姓名和款项。这些信息被存储在一个动态分配的结构数组中。每个结构有两个成员:用来存储姓名的字符数组(或string对象)和用来存储款项的double成员。读取所有的数据后,程序将会显示所有捐款超过10000的捐款者姓名及其捐款数额。该列表前应包含一个标题,指出下面的捐款者是重要捐款人(Grand Patrons)。然后,程序将列出其他的捐款者,该列表以Patrons开头。如果某种类别没有捐款者,则程序将打印单词“none”。该程序只显示这两种类别,而不进行排序。
#include <iostream>
#include <cstring>
​
struct donors
{
    char name[20];
    double money;
};
​
int main()
{
    using namespace std;
    cout << "本程序记录捐助给“维护合法权利团体”的资金,将要求您输入捐献者数目:" << endl;
    int number_donors = 0;
    while (cin) {
        if (!(cin >> number_donors)) {
            cout << "请输入一个正确的数字:";
            continue;
        }
        else {
            break;
        }
    }
    donors* members = new donors[number_donors];
    char name[20];
    double money;
    for (int i = 0; i < number_donors; i++) {
        cout << i + 1 << "#:" << "姓名:" << endl;
        cin.get();
        cin.getline(name, 19);
        cout << "捐款数额:" << endl;
        if (!(cin >> money)) {
            cout << "输入有误,请重新输入!" << endl;
            i--;
            continue;
        }
        members[i].money = money;
        strcpy_s(members[i].name, name);
    }
    //遍历数额
    cout << "Grand Patrons:" << endl;
    {
        int j = 0;
        for (int i = 0; i < number_donors; i++) {
            if (members[i].money > 10000) {
                cout << members[i].name << endl;
                j++;
            }
        }
        if (j == 0) {
            cout << "None\n";
        }
    }
    cout << "Patrons:" << endl;
    {
        int j = 0;
        for (int i = 0; i < number_donors; i++) {
            if (members[i].money <= 10000) {
                cout << members[i].name << endl;
                j++;
            }
        }
        if (j == 0) {
            cout << "None\n";
        }
    }
    delete[] members;
}
7.编写一个程序,它每次读取一个单词,直到用户只输入q。然后,该程序指出有多少个单词以元音打头,有多少个单词以辅音打头,还有多少单词不属于这两类。为此,方法之一是,使用isalpha()来区分以字母和其他字符打头的单词,然后对于通过了isalpha()测试的单词,使用if或switch语句来确定哪些以元音打头。该程序运行情况如下:

The 12 awesome oxen ambled quoetly across 15 meters of lawn. q 5words beginning with vowels 4words beginning with consonants 2 others

#include <iostream>
#include <cctype>
​
int main()
{
    using std::cout;
    using std::cin;
    using std::endl;
    char ch[20];
    char initial[50];//存储首字母
    cout << "Enter words (q to quit):" << endl;
    int i = 0;//记录每个单词首字母位置
    while (cin >> ch) {
        if ((ch[0] == 'q') and (ch[1] == '\0')) {
            break;
        }
        else {
            initial[i] = ch[0];
            i++;
        }
    }
    int count_vowels = 0;//记录元音
    int count_consonants = 0;//记录辅音
    int count_others = 0;
    for (int j = 0; j < i; j++) {//遍历数组结构
        char tmp = initial[j];
        if (std::isalpha(tmp))//判断是否为字母
        {
            switch (tmp)
            {
            case 'A':
            case 'a':
            case 'E':
            case 'e':
            case 'I':
            case 'i':
            case 'O':
            case 'o':
            case 'U':
            case 'u':
                count_vowels++;
                break;
            default:
                count_consonants++;
                break;
            }
        }
        else {
            count_others++;
        }
    }
    cout << "vowels:" << count_vowels << endl;
    cout << "consonants:" << count_consonants << endl;
    cout << "others:" << count_others << endl;
}
8.编写一个程序,它打开一个文本文件,逐个字符的读取该文件,直到达到文件末尾,然后指出该文件包含多少个字符。
#include <iostream>
#include <fstream>
#include <cstdlib>  //exit()的所在库
​
int main()
{
    using namespace std;
    ifstream inFile;
    inFile.open("test.txt");
    if (!inFile.is_open()) {
        cout << "找不到该文件!" << endl;
        exit(EXIT_FAILURE);
    }
    long long sum = 0;
    char ch;
    inFile >> ch;
    while (inFile.good()) {
        ++sum;
        inFile >> ch;
    }
    if (inFile.eof()) {
        cout << "End of file reached.\n";
    }
    else if (inFile.fail()) {
        cout << "Input terminated by data mismatch.\n";
    }
    else
        cout << "Input terminated for unknown reason.\n";
    if (sum == 0)
        cout << "No data\n";
    else
        cout << "sum:" << sum << endl;
    inFile.close()
}
9.完成编程练习6,但从文件中读取所需的信息。该文件的第一项应为捐款人物,余下的内容应为成对的行。在每一对中,第一行为捐款人姓名,

第二行为捐款数额。即该文件类似于下面: 4 Sam Stone 2000 Freida Flass 100500 Tammy Tubbs 5000 Rich Raptor 55000

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    ifstream infile;
    infile.open("111.txt");
    int number;
    infile >> number;
    infile.get();
    struct patron
    {
        char name[20];
        double money;
    };
    patron* p = new patron[number];
    for (int i = 0; i < number; i++)
    {
        infile.getline(p[i].name, 20);
        infile >> p[i].money;
        infile.get();
    }
    bool rich = false;
    bool poor = false;
    for (int i = 0; i < number; i++)
    {
        if (p[i].money > 10000)
        {
            rich = true;
        }
        if (p[i].money <= 10000)
        {
            poor = true;
        }
    }
    if (rich == true && poor == true)
    {
        cout << "Grand Patrons" << endl;
        for (int i = 0; i < number; i++)
        {
            if (p[i].money > 10000)
            {
                cout << p[i].name << " " << p[i].money << endl;
            }
        }
        cout << "Patrons" << endl;
        for (int i = 0; i < number; i++)
        {
            if (p[i].money <= 10000)
            {
                cout << p[i].name << " " << p[i].money << endl;
            }
        }
    }
    else if (rich == true && poor == false)
    {
        cout << "Grand Patrons" << endl;
        for (int i = 0; i < number; i++)
        {
            if (p[i].money > 10000)
            {
                cout << p[i].name << " " << p[i].money << endl;
            }
        }
        cout << "Patrons" << endl;
        cout << "none" << endl;
    }
    else if (rich == false && poor == true)
    {
        cout << "Grand Patrons" << endl;
        cout << "none" << endl;
        cout << "Patrons" << endl;
        for (int i = 0; i < number; i++)
        {
            if (p[i].money <= 10000)
            {
                cout << p[i].name << " " << p[i].money << endl;
            }
        }
    }
    delete[]p;
    infile.close();
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值