[C++ Primer Plus] 第6章、分支语句和逻辑运算符(二)课后习题

一、复习题

3.

#include<iostream>
using namespace std;

void main()
{
    char ch;
    int c1, c2;
    c1 = c2 = 0;

    while ((ch=cin.get())!='$')
    {
        cout << ch;
        c1++;
        if (ch = '$')    //注意是=,不是==
            c2++;
        cout << ch;
    }
    cout << "c1=" << c1 << ",c2=" << c2 << endl;

    system("pause");
}

二、编程练习

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

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

void main()
{
    char ch;
    while ((ch = cin.get()) && ch != '@')
    {
        if (!isdigit(ch)) {
            if (islower(ch)) //如果是小写字符      
                ch = toupper(ch);//转化为大写
            else if (isupper(ch))
                ch = tolower(ch);
            cout << ch;
        }
    }
    
    system("pause");
}

2. 编写一个程序,最多将10个donation值读到一个double数组中。程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。

#include<iostream>
using namespace std;

const int SIZE = 10;
void main()
{
    double donation[10], sum = 0.0,average;
    int i,count=0;
    for (i = 0; i < SIZE; i++)
    {
        if (cin >> donation[i])
            sum += donation[i];
        else
            break;//退出最近的循环,即退出for循环
    }
    if (i == 0)
        return;
    else
        average = sum / i;
    for (int j = 0; j < i; j++)
    {
        if (donation[j] > average)
            count++;
    }
    cout << "average=" << average << "," << count << " numbers bigger than average." << endl;
    
    system("pause");
}

3.编写一个菜单驱动程序的雏形。该程序显示一个提供4个选项的菜单——每个选项用一个字母标记。如果用户使用有效选项之外的字母进行响应,程序将提示用户输入一个有效的字母,直到用户这样做为止。然后,该程序使用一条switch语句,根据用户的选择执行一个简单的操作。

#include<iostream>
using namespace std;

void showA() {
    cout << "Please enter one of the following choices:
"
         << "a) carnivore	" << "b) pianist
"
         << "c) tree		"    << "d) game
";
}

void main()
{
    showA();
    char ch;
    cin >> ch;
    int flag = 0;
    while (1)
    {
        switch (ch)
        {
        case 'a':cout << "A maple is a carnivore." << endl;
            flag = 1;
            break;
        case 'b':cout << "A maple is a pianist." << endl;
            flag = 1;
            break;
        case 'c':cout << "A maple is a tree." << endl;
            flag = 1;
            break;
        case 'd':cout << "A maple is a game." << endl;
            flag = 1;
            break;
        default:cout << "Please enter a,b,c,d :";
            cin >> ch;
        }
        if (flag)
            break;
    }
    system("pause");
}

 4. 加入Benevolent Order of Programmer后,在BOP大会上,人们便可以通过加入者的真实姓名、头衔或秘密BOP姓名来了解他,请编写一个程序,可以使用真实姓名、头衔、秘密姓名或成员偏好来列出成员。编写该程序时,请使用下面结构

//Benevolent Order of Programmers name structure

Struct bop

{

char fullname[strsize];

char title[strsize];

char bopname[strsize];

int preference;

};

该程序创建一个由上述结构组成的小型数组,并将其初始化为适当的值,另外,该程序使用一个循环让用户在下面的选项中进行选择:

A. Display by name B. Display by title C. Display by bopname

D. Display by preference Q. quit

#include<iostream>
using namespace std;

const int strsize = 20,num=10;
struct bop
{
    char fullname[strsize]; //真实姓名  
    char title[strsize];    //头衔  
    char bopname[strsize];  //秘密姓名  
    int preference;     //偏好,当为0时为fullname,1为title,2为bopname  
};

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

void main()
{
    bop p[num] = {
        { "王一","程序员","first",0 },
        { "张二", "老师", "2nd",1 },
        { "李三", "公务员", "3rd",2 },
        { "赵四", "咨询师", "4th",0 },
        { "南宫五", "理发师", "5th",1 },
        { "龙六", "玩家", "6th", 2 }
    };
    char ch;
    show();
    int flag = 0;
    cout << "Enter your choice:";
    int l = sizeof(p)/sizeof(p[0]);
    while (cin>>ch)
    {
        switch (ch)
        {
        case 'a':
            for (int i = 0; i < num&&strlen(p[i].fullname) != 0; i++)
                cout << p[i].fullname << endl;
            break;
        case 'b':
            for (int i = 0; i < num&&strlen(p[i].fullname) != 0; i++)
                cout << p[i].title << endl;
            break;
        case 'c':
            for (int i = 0; i < num&&strlen(p[i].fullname) != 0; i++)
                cout << p[i].bopname << endl;
            break;
        case 'd':
            for (int i = 0; i < num&&strlen(p[i].fullname) != 0; i++)
            {
                switch (p[i].preference)
                {
                case 0:cout << p[i].fullname << endl;
                    break;
                case 1:cout << p[i].title << endl;
                    break;
                case 2:cout << p[i].bopname << endl;
                    break;
                }
            }
            break;
        case 'q':
            flag = 1;
            cout << "Bye!
";
            break;
        default:
            cout << "Enter error!";
            break;
        }
        if (flag)
            break;
        cout << "Next choice:";
    }
    system("pause");
}

5.在Ncutronia王国,货币单位是tvarp,收入所得税的计算方式如下:

5000 tvarps:不收税

5001~15000 tvarps: 10%

15001~35000 tvarps: 15%

35000 tvarps以上: 20%

例如,收入为38000 tvarps时,所得税为5000x0.00 + 10000x0.10 + 20000x0.15+3000x0.20,即4600 tvarps。请编写一个程序,使用循环来要求用户输入收入,并报告所得税。当用户输入负数或非数字时,循环将结束。

#include<iostream>
using namespace std;

void main()
{
    double money;
    cout << "请输入您的收入:";
    while (cin>>money)
    {
        if (money < 0)
            break;
        else if (money <= 5000)
            cout << "不交税" << endl;
        else if (money <= 15000)
            cout << (money - 5000)*0.1 << endl;
        else if (money <= 35000)
            cout <<10000*0.1+(money - 15000)*0.15 << endl;
        else 
            cout << 10000 * 0.1 +20000*0.15+ (money - 35000)*0.2 << endl;
        cout << "请输入您的收入:";
    }
    
    system("pause");
}

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

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

struct donation
{
    string name;
    double money;
};

void main()
{
    cout << "请输入捐献者数量:";
    int num;
    cin >> num;
    int s[5] = { 0 };
    donation *p = new donation[num];

    for (int i = 0; i < num; i++)
    {
        cout << "请输入第" << (i + 1) << "个捐献者的姓名:";
        cin >> p[i].name;
        cout << "请输入第" << (i + 1) << "个捐献者的捐款数额:";
        cin >> p[i].money;
    }
    int flag = 0;//标示,判断是否打印“none”
    cout << "重要捐款人如下:" << endl;
    for (int i = 0; i < num; i++)
    {
        if (p[i].money > 10000)
        {
            cout << p[i].name << "捐款" << p[i].money << "" << endl;
            flag = 1;
        }
    }
    if (flag == 0)
        cout << "none" << endl;
    flag = 0;
    cout << "其他捐款人如下:" << endl;
    for (int i = 0; i < num; i++)
    {
        if (p[i].money <= 10000)
        {
            cout << p[i].name << "捐款" << p[i].money << "" << endl;
            flag = 1;
        }
    }
    if (flag == 0)
        cout << "none" << endl;
    delete p[];//用完new一定要记得delete
    system("pause");
}

7.编写一个程序,他每次读取一个单词,直到用户只输入q。然后,该程序指出有多少单词以元音打头,有多少个单词以辅音打头,还有多少单词不属于这两类。为此,方法之一是使用isalpha()来区分以字母和其他字符打头的单词,然后对于通过salpha()测试的单词,使用if或switch语句来确定哪些是以元音打头。

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

void main()
{
    cout << "Enter words (q to quit):" << endl;
    char ch;
    cin.get(ch);
    int vowel = 0, consonant = 0, other = 0, flag = 1;
    while (ch != 'q')
    {
        if (isalpha(ch)) {//如果参数是字母,返回true
            if (flag)
            {
                switch (ch) {
                case 'a':
                case 'A':
                    vowel++;
                    flag = 0;    break;
                case 'e':
                case 'E':
                    vowel++;
                    flag = 0;    break;
                case 'i':
                case 'I':
                    vowel++;
                    flag = 0;    break;
                case 'o':
                case 'O':
                    vowel++;
                    flag = 0;    break;
                case 'u':
                case 'U':
                    vowel++;
                    flag = 0;    break;
                default:
                    consonant++;
                    flag = 0;    break;
                }
            }
        }
        else if (isspace(ch) || ispunct(ch))//如果参数是空格、tab、换行等空白字符,或者是标点符号,返回true
            flag = 1;
        else {
            if (flag)
            {
                other++;
                flag = 0;
            }
        }
        cin.get(ch);
    }
    cout << vowel << " words beginning with vowels " << endl;
    cout << consonant << " words beginning with consonants " << endl;
    cout << other << " others" << endl;
    system("pause");
}

这是一串有问题的代码,找了半天实在不知道错在哪,先贴在这儿,看以后能发现错误不

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

#include<iostream>
#include<fstream>//文件IO
using namespace std;

void main()
{
    ifstream inFile;//声明ifstream对象
    inFile.open("1.txt");//关联文件

    if (!inFile.is_open())//文件打开失败
    {
        cout << "Could not open the file " << endl;
        exit(EXIT_FAILURE);
    }
    char ch;
    int count = 0;

    inFile >> ch;
    while (inFile.good())//输入正确
    {
        ++count;
        cout << ch;
        inFile >> ch;
    }
    cout << endl;

    if (inFile.eof())
        cout << "End of file reached." << endl;
    else if (inFile.fail())
        cout << "Input terminated by data misamatch." << endl;
    else
        cout << "Input terminated for unknown reason." << endl;
    
    cout << "文件包含" << count<<"个字符" << endl;
    inFile.close();

    system("pause");
}

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

4

Sam Stone

2000

Freida Flass

100500

Tammy Tubbs

5000

Rich Raptor

55000

#include<iostream>
#include<fstream>//文件IO
#include<string>
using namespace std;

struct donation
{
    string name;
    double money;
};
void main()
{
    ifstream inFile;//声明ifstream对象
    inFile.open("1.txt");//关联文件
    if (!inFile.is_open())//文件打开失败
    {
        cout << "Could not open the file " << endl;
        exit(EXIT_FAILURE);
    }

    int num, i = 0;
    inFile >> num;
    inFile.get();//抵消换行
    donation *p = new donation[num];
    for (int i = 0; i < num; i++)
    {
        getline(inFile, p[i].name);
        inFile >> p[i].money;
        inFile.get();//抵消换行
    }
    
    int flag = 0;//标示,判断是否打印“none”
    cout << "重要捐款人如下:" << endl;
    for (int i = 0; i < num; i++)
    {
        if (p[i].money > 10000)
        {
            cout << p[i].name << "捐款" << p[i].money << "" << endl;
            flag = 1;
        }
    }
    if (flag == 0)
        cout << "none" << endl;
    flag = 0;
    cout << "其他捐款人如下:" << endl;
    for (int i = 0; i < num; i++)
    {
        if (p[i].money <= 10000)
        {
            cout << p[i].name << "捐款" << p[i].money << "" << endl;
            flag = 1;
        }
    }
    if (flag == 0)
        cout << "none" << endl;

    if (inFile.eof())
        cout << "End of file reached." << endl;
    else if (inFile.fail())
        cout << "Input terminated by data misamatch." << endl;
    else
        cout << "Input terminated for unknown reason." << endl;

    inFile.close();
    delete [] p;//用完new一定要记得delete
    system("pause");
}

原文地址:https://www.cnblogs.com/little-monkey/p/7525949.html