C++ primer Plus(第六版)中文版 第六章 分支语句和逻辑运算符 编程练习答案

本博客详细介绍了多个C++编程实例,包括字符转换、数组处理、菜单驱动程序、结构体应用、文件读取等核心概念的实践操作。通过具体案例,读者可以深入理解并掌握C++的分支语句、逻辑运算符、文件操作及结构体的运用。

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

第六章 分支语句和逻辑运算符
1. 编写一个程序,读取键盘输入,直到遇到@符号为止,并回显输入(数字除外),
    同时将大写字符转换为小写,将小写字符转换为大写(别忘了cctype函数系列)。

1.1 使用 if-else-if

#include <iostream>

int main()
{
    using namespace std;
    char a;
    
    cin >> a;                      //或cin.get(a);    //再或a=cin.get(); 
    while(a !='@')
    {
        if (isupper(a))
        {
            a = tolower(a);
            cout << a;
        }
        else if (islower(a))
        {
            a = toupper(a);
            cout << a;
        }
        cin >> a;                  //或cin.get(a);    //再或a=cin.get(); 
    }
    return 0;
}

//或者

#include <iostream>

int main()
{
    using namespace std;
    char a;
    
    while(cin >> a && a !='@')     //或 while(cin.get(a) && a !='@')  
    {
        if (isupper(a))
        {
            a = tolower(a);
            cout << a;
        }
        else if (islower(a))
        {
            a = toupper(a);
            cout << a;
        }
    }
    return 0;
}


2.1 使用 if+continue   

#include <iostream>

int main()
{
    using namespace std;
    char a;
    
    while(cin >> a && a !='@')
    {
        if (isupper(a))
        {
            a = tolower(a);
            cout << a;
            continue;
        }
        if (islower(a))
        {
            a = toupper(a);
            cout << a;
            continue;
        }
    }
    return 0;
}
    

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

2.1 版本1

#include <iostream>

int main()
{
    using namespace std;
    double donation[10];
    int i = 0;
    double sum = 0;
    double average = 0;
    int num = 0;
    
    cout << "最多输入10个数字,输入任意非数字结束\n";
    while (i < 10 && cin >> donation[i])
    {
        sum = sum + donation[i];
        i++;
        average = sum/i;
    }
    
    for (int j = 0; j < 10; j++)
    {
        if (donation[j] > average)
            num++;
    }
    
    cout << "数组中共有" << i << "个数,其中大于平均值" << average << "的有" << num << "个。";

    return 0;
}


2.2 版本2

#include <iostream>

int main()
{
    using namespace std;
    double donation[10];
    int i = 0;
    double sum = 0;
    double average = 0;
    int num = 0;
    
    cout << "最多输入10个数字,输入任意非数字结束\n";
    
    for (i = 0; i < 10; i++)
    {
        if(cin >> donation[i])
        {
            sum = sum + donation[i];
            average = sum /(i+1);
        }
        else 
            break;
    }
    
    for (int j = 0; j < 10; j++)
    {
        if (donation[j] > average)
            num++;
    }
    
    cout << "数组中共有" << i << "个数,其中大于平均值" << average << "的有" << num << "个。";

    return 0;
}

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

#include <iostream>

int main()
{    
    using namespace std;
    char a;
    
    cout << "Please enter one of the following choices:\n";
    cout << "c) carnivore                p) pianist\n";
    cout << "t) tree                     g) game\n";
    
    while(cin >> a)
    {
        switch (a)
        {
            case 'c' : cout << "A maple is a carnivore.";
                       break;
            case 'p' : cout << "A maple is a pianist.";
                       break;
            case 't' : cout << "A maple is a tree.";
                       break;
            case 'g' : cout << "A maple is a game.";
                       break;         
            default  : cout << "Please enter a c, p, t, or g: ";
        }
    }
    
    return 0;
}

4. 加入Benevolent Order of Programmer后,在BOP大会上,人们可通过加入者的真实姓名、头衔或秘密BOP来了解他(她)。
    请编写一个程序,可以使用真实姓名、头衔、秘密姓名或成员preference(书中翻译为偏好,个人认为应该翻译为优先权)来      列出成员。编写该程序时,请使用下面的结构:
    //Benevolent Order of Programmers name structure
    struct bop{
        char fullname[strsize];
        char title[strsize];
        char bopname[strsize];
        int preference;        // 0 = fullname, 1 = title, 2 = bopname
    };
    该程序创建一个由上述结构组成的小型数组,并将其初始化为适当的值。
    另外,该程序是用一个循环,让用户在下面的选项中进行选择:
    a. display by name            b. display by title
    c. display by bopname         d. display by preference
    q. quit
    注意,“display by preference”,并不意味着显示成员的preference,而是意味着根据成员的preference来列出成员。
    例如:如果preference为1,则选择d将显示程序员的头衔。该程序运行情况如下:
Benevolent Order of Programmers Report
a. display by name            b. display by title
c. display by bopname         d. display by preference
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>

void choice_a();
void choice_b();
void choice_c();
void choice_d();

const int strsize = 30;
const int num =5; 
char a;
    
struct bop{
    char fullname[strsize];
    char title[strsize];
    char bopname[strsize];
    int preference;        // 0 = fullname, 1 = title, 2 = bopname
};
    
bop number[num] = 
{
    {"Wimp Macho", "WM头衔", "WM秘密姓名",0},
    {"Raki Rhodes", "Junior Programmer","RR秘密姓名",1},
    {"Celia Laiter", "CL头衔","MIPS",2},
    {"Hoppy Hipman", "Analyst Trainee","HH秘密姓名",1},
    {"Pat Hand", "PH头衔","LOOPY",2}
};

int main()
{
    using namespace std;

    
    cout << "Benevolent Order of Programmers Report\n";
    cout << "a. display by name            b. display by title\n";
    cout << "c. display by bopname         d. display by preference\n";
    cout << "q. quit\n";
    
    cout << "Enter your choice: ";
    
    while(cin >> a && a != 'q')
    {
        switch (a)
        {
            case 'a' : choice_a();
                       break;
            case 'b' : choice_b();
                       break;
            case 'c' : choice_c();
                       break;
            case 'd' : choice_d();
                       break;        
            default  : cout << "Please enter a a, b, c, or d: ";
        }
        cout << "Next choice: ";
    }
    
    cout << "Bye!";
    return 0;
}

void choice_a()
{
    using namespace std;
    for (int i = 0; i < num; i++)
        cout << number[i].fullname << endl;
}

void choice_b()
{
    using namespace std;
    for (int i = 0; i < num; i++)
        cout << number[i].title << endl;
}

void choice_c()
{
    using namespace std;
    for (int i = 0; i < num; i++)
        cout << number[i].bopname << endl;
}

void choice_d()
{
    using namespace std;
    for (int i = 0; i < num; i++)
    {
        if (number[i].preference == 0)
            cout << number[i].fullname << endl;
        else if (number[i].preference == 1)
            cout << number[i].title << endl;
        else if (number[i].preference == 2)
            cout << number[i].bopname << endl;
    }    
}    

5. 在Neutronia王国,货币单位是tvarp,收入所得税的计算方式如下:
   5000 tvarp:不收税
   5001~15000 tvarps: 10%
   15001~35000 tvarps: 15%
   35000 tvarps以上: 20%

5.1 版本1

#include <iostream>

int main()
{
    using namespace std;
    unsigned double income;
    unsigned double tax;
    
    cout << "请输入您的收入(tvarp):";
    while(cin >> income)
    {
        if (income <= 5000)
            tax = 0;
        else if (income <= 15000)
            tax = (income-5000)*0.1;
        else if (income <= 35000)
            tax = (income-15000)*0.15 + (15000-5000)*0.1;
        else
            tax = (income-35000)*0.2 + (35000-15000)*0.15 + (15000-5000)*0.1;
        cout << "您的所得税金额为:" << tax << "tvarp";
    }

    cout << "end";

    return 0;
}    

5.2 版本2

#include <iostream>
int main()
{   
    using namespace std;
    
    double income;
    double tax;
    cout << "请输入收入金额:";
    while(cin >> income && income > 0)
    {
        double a = income-5000;
        if (a > 0)
        {
            double b = a - 10000;
            if (b > 0)
            {
                double c = b - 20000;
                if (c > 0)
                    tax = 5000*0.00+10000*0.1+20000*0.15+c*0.20;
                else
                    tax = 5000*0.00+10000*0.1+b*0.15;
            }
            else
                tax = 5000*0.00+a*0.1;
        }
        else
            tax = 0;
        cout << "收入为" << income << "tvarps时,所得税为" << tax <<"tvarps\n";
    }
    
    return 0;
}    

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

6.1 版本1   

#include <iostream>

int main()
{
    using namespace std;

    struct message
    {
        char name[20];
        double money;
    };
    int num;
    int j = 0;
    int k = 0;
    
    cout << "请输入捐献者的数目:";
    cin >> num;
    cin.get();
    message* full = new message [num];
    
    for (int i = 0; i < num; i++)
    {
        cout << "请输入第" << i+1 << "位捐款者的姓名:";
        cin.get(full[i].name, 20).get();
        cout << "请输入第" << i+1 << "位捐款者的数额:";
        cin >> full[i].money;
        cin.get();
    }
    
    cout << "Grand Patrons:\n";
    for (int i = 0; i < num; i++)
    {
        if (full[i].money > 10000)
        { 
            cout << full[i].name << "\t\t\t" << full[i].money << endl;
            j++;
        }
    }
    if(j == 0)
        cout << "none\n";  
    
    cout << "Patrons:\n";
    for (int i = 0; i < num; i++)
    {
        if (full[i].money <= 10000)
        {
            cout << full[i].name << "\t\t\t" << full[i].money << endl;
            k++;
        }
    }
    if(k == 0)
        cout << "none\n";

    return 0;
}

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

7.1 版本1

#include <iostream>
#include <string>
#include <cctype>

int isvowels(char);

int main()
{
    using namespace std;
    
    string word;
    int i = 0;
    int j = 0;
    int k = 0;
    
    cout << "Enter words (q to quit):\n";

    while (cin >> word && word!="q")
    {
        if(isalpha(word[0]))
        {
            if (isvowels(word[0]))
                i++;
            else
                j++;
        }
        else
            k++;
    }
    
    cout << i << " words beginning with vowels\n";
    cout << j << " words beginning with consonants\n";
    cout << k << " others";
    
    return 0;
}
 
int isvowels(char a)
{
    a = tolower(a);
    if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
        return 1;
    else 
        return 0;
}

7.2 版本2

#include <iostream>
#include <string>
#include <cctype>

int main()
{   
    using namespace std;
    string str;
    int i = 0;
    int n = 0;
    int t = 0;
    
    cout << "Enter words (q to quit):\n";
    while (cin >> str)
    {
        if (str.length()==1 && str[0]=='q')
            break;
        else
        {
        if (isalpha(str[0]))
        {
            if (str[0] == 'a' || str[0] == 'e' || str[0] == 'i' || str[0] == 'o' || str[0] == 'u'
                || str[0] == 'A' || str[0] == 'E' || str[0] == 'I' || str[0] == 'O' || str[0] == 'U')
                i++;
            else 
                n++;
        } 
        else
            t++;
        }
    }
    
    cout << i << "words beginning with vowels\n";
    cout << n << "words beginning with consonants\n";
    cout << t << "others";
    
    return 0;
}

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

#include <iostream>
#include <fstream>
#include <cstdlib>

int n = 0;
int main()
{
    using namespace std;
    ifstream inFile;             //声明ifstream对象
    inFile.open("123.txt");      //将ifstream对象与特定文件关联
    if (!inFile.is_open())       //检查是否正确打开文件
    {
        exit(EXIT_FAILURE);
    }
    
    char ch;
    while(ch = inFile.get() != EOF)
        n += 1;
    cout << n;
    
    return 0;
}

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

#include <iostream>
#include <fstream>
#include <cstdlib>

int main()
{
    using namespace std;

    struct message
    {
        char name[20];
        double money;
    };
    int num;
    int j = 0;
    int k = 0;
    
    ifstream inFile;                 //声明ifstream对象
    inFile.open("excise6.txt");      //将ifstream对象与特定文件关联
    if (!inFile.is_open())           //检查是否正确打开文件
    {
        exit(EXIT_FAILURE);
    }
    
    
    cout << "请输入捐献者的数目:";
    inFile >> num;
    inFile.get();
    message* full = new message [num];
    
    for (int i = 0; i < num; i++)
    {
        cout << "请输入第" << i+1 << "位捐款者的姓名:";
        inFile.get(full[i].name, 20).get();
        cout << "请输入第" << i+1 << "位捐款者的数额:";
        inFile >> full[i].money;
        inFile.get();
    }
    
    cout << "Grand Patrons:\n";
    for (int i = 0; i < num; i++)
    {
        if (full[i].money > 10000)
        { 
            cout << full[i].name << "\t\t\t" << full[i].money << endl;
            j++;
        }
    }
    if(j == 0)
        cout << "none\n";  
    
    cout << "Patrons:\n";
    for (int i = 0; i < num; i++)
    {
        if (full[i].money <= 10000)
        {
            cout << full[i].name << "\t\t\t" << full[i].money << endl;
            k++;
        }
    }
    if(k == 0)
        cout << "none\n";

    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值