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

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

 1 #include<iostream>
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     char ch;
 7     while (cin.get(ch) && ch != '@')
 8     {
 9         if (isupper(ch))
10             ch = tolower(ch);
11         else if (islower(ch))
12             ch = toupper(ch);
13         else if (isdigit(ch))
14             continue;
15             cout << ch;
16     }
17     system("pause");
18     return 0;
19 }

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

 1 #include<iostream>
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     double donation[10];
 7     double average, sum = 0;
 8     int cnt = 0, i;
 9     for ( i = 0; i < 10; i++)
10     {
11         if (cin >> donation[i])      //返回bool类型的值,用来判断输入是否有效
12         {
13             sum += donation[i];
14         }
15         else
16             break;
17     }
18     average = sum / i;
19     for (int j = 0; j < i; j++)
20     {
21         if (donation[j] > average)
22             cnt++;
23     }
24     cout << "The average is " << average << endl;
25     cout << "Greater than the average is " << cnt << endl;
26 
27     system("pause");
28     return 0;
29 }

 

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

  Please enter one of the following choices:

  c) carnivore    p) pianist

  t) tree        g) game

  f

  Please enter a c, p, t, or g: q

  Please enter a c, p, t, or g: t

  A maple is a tree.

 1 #include<iostream>
 2 using namespace std;
 3 
 4 void showmenu();
 5 
 6 int main()
 7 {
 8     showmenu();
 9     char choice;
10     int flag = 1;
11     while (flag)
12     {
13         cin >> choice;
14         switch (choice)
15         {
16         case 'c': cout << "A maple is a carnivore." << endl;
17             flag = 0;
18             break;
19         case'p':cout << "A maple is a pianist." << endl;
20             flag = 0;
21             break;
22         case't':cout << "A maple is a tree." << endl;
23             flag = 0;
24             break;
25         case'g':cout << "A maple is a game." << endl;
26             flag = 0;
27             break;
28         default:cout << "Please enter a c, p, t, or g: ";
29             flag = 1;
30         }
31     }
32     system("pause");
33     return 0;
34 }
35 
36 void showmenu()
37 {
38     cout << "Please enter one of the following choices:\n"
39             "c) carnivore      p) pianist\n"
40             "t) tree         g) game\n";
41 }

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

  //Benevolent Order of Programmer name structure

  struct bop{

    char fullname[strsize];  // real name

    char title[strsize];  // job title

    char bopname[strsize];  // secret BOP name

    int preference;  // 0 = fulname, 1 = title, 2 = bopname 

  }

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

  a. display by name    b.display by title

  c.display by bopname    d.diaplay by preference

  q.quit

   注意,“diaplay by preference”并不意味着显示成员的偏好,而是意味着根据成员的偏好来列出成员。例如,如果偏好号为1,则选择d将显示程序员的头衔。

 1 #include<iostream>
 2 #include<cstring>
 3 using namespace std;
 4 
 5 const int strsize = 20;
 6 void showmenu();
 7 
 8 struct bop
 9 {
10     char fullname[strsize];    // real name
11     char title[strsize];    // job title
12     char bopname[strsize];    // secret BOP name
13     int preference;      // 0 = fulname, 1 = title, 2 = bopname 
14 };
15 
16 int main()
17 {
18     bop list[5] = { { "Wimp Macho", "W", "Wimp", 0 }, { "Raki Rhodes", "R", "Raki", 1 }, { "Celia Laiter", "C", "Celia", 2 }, { "Hoppy Hipman", "H", "Hoppy", 0 }, { "Pat Hand", "P", "Pat", 1 } };
19     showmenu();
20     char choice;
21     int flag = 1;            //注意q的处理
22     while (flag)
23     {
24         cin >> choice;
25         switch (choice)
26         {
27         case'a':for (int i = 0; i < 5; i++)
28         {
29             cout << list[i].fullname << endl;
30         }
31                 break;
32         case 'b': for (int i = 0; i < 5; i++)
33         {
34             cout << list[i].title << endl;
35         }
36                   break;
37         case 'c': for (int i = 0; i < 5; i++)
38         {
39             cout << list[i].bopname << endl;
40         }
41                   break;
42         case'd':for (int i = 0; i < 5; i++)
43         {
44             if (list[i].preference == 0)
45                 cout << list[i].fullname << endl;
46             else if (list[i].preference == 1)
47                 cout << list[i].title << endl;
48             else
49                 cout << list[i].bopname << endl;
50         }
51                 break;
52         case'q':flag = 0;
53             cout << "Bye!" << endl;
54             break;
55         default:cout << "This is invalid input!" << endl;
56         }
57         if (flag == 0)
58             break;
59         cout << "Next choice: ";
60     }
61     system("pause");
62     return 0;
63 }
64 
65 void showmenu()
66 {
67     cout << "Benevolent Order of Programmers Report" << endl
68          << "a. display by name  \t" << "b.display by title" << endl
69           << "c.display by bopname\t" << "d.diaplay by preference" << endl
70          << "q.quit" << endl;
71     cout << "Enter your choice: ";
72 }

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

  5000 tvarps:不收税

  5001~15000 tvarps:10%

  15001~35000 tvarps:15%

  35000 tvarps以上:20%

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

 1 #include<iostream>
 2 #include<cstring>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     double income, tax;
 8     cout << "Please enter income: ";
 9     while (cin >> income)
10     {
11         if (income <= 5000)
12             tax = 0;
13         else if (income > 5000 && income <= 15000)
14             tax = (income - 5000)*0.10;
15         else if (income > 15000 && income <= 35000)
16             tax = 10000 * 0.10 + (income - 15000)*0.15;
17         else if (income > 35000)
18             tax = 10000 * 0.10 + 20000 * 0.15 + (income - 35000)*0.20;
19         cout << "Tax= " << tax << endl;
20         cout << "Please enter income again: ";
21     }
22     cout << "Invalid input!" << endl; 
23 
24     system("pause");
25     return 0;
26 }

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

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 struct stream
 6 {
 7     string name;
 8     double donation;
 9 };
10 
11 int main()
12 {
13     int n, i, flag = 0;
14     cout << "Please enter the number of contributors: ";
15     cin >> n;
16     stream *str = new stream[n];       //创建的动态结构数组
17     for (i = 0; i < n; i++)
18     {
19         cout << "Enter name: ";
20         cin >> str[i].name;
21         cout << "Enter donation: ";
22         cin >> str[i].donation;
23     }
24     cout << endl;
25     cout << fixed;
26     cout.precision(2);
27     cout.setf(ios_base::showpoint);
28     cout << "Grand Patrons:";
29     for (i = 0; i < n; i++)
30     {        
31         if (str[i].donation>10000)
32         {
33             cout << str[i].name << "\t" << str[i].donation << endl;
34             flag = 1;
35         }
36     }
37     cout << endl;
38     if (flag == 0)
39     {
40         cout << "None" << endl;
41     }
42     cout << endl;
43     cout << "Other Patrons:" << endl;
44     for (i = 0; i < n; i++)
45     {
46         if (str[i].donation <= 10000)
47         {
48             cout << str[i].name << "\t" << str[i].donation << endl;
49             flag = 1;
50         }
51         if (flag == 0)
52         {
53             cout << "None" << endl;
54         }
55     }
56     delete[]str;                  //记得delete
57     system("pause");
58     return 0;
59 }

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

  Enter words (q to quit):

  The 12 awesome oxen ambled

  quietly across 15 meters od lawn. q

  5 words beginning with vowels

  4 words beginning with consonants

  2 others

 1 #include<iostream>
 2 #include<string>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     char sen[20];
 8     int i, yuan = 0, fu = 0, other = 0;
 9     cout << "Enter words (q to quit): " << endl;
10     cin >> sen;
11     while (strcmp(sen, "q"))
12     {
13         if (isalpha(sen[0]))
14         {
15             switch (sen[0])
16             {
17             case'a':
18             case'A':
19             case'e':
20             case'E':
21             case'i':
22             case'I':
23             case'o':
24             case'O':
25             case'u':
26             case'U':yuan++; break;
27             default:fu++;
28             }
29         }
30         else other++;
31         cin >> sen;
32     }
33     cout << yuan << " words beginning with vowels" << endl;
34     cout << fu << " words beginning with consonants" << endl;
35     cout << other << " others" << endl;
36     system("pause");
37     return 0;
38 }

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

 1 #include<iostream>
 2 #include<fstream>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     ifstream inFile;
 8     char filename[60];
 9     cout << "Enter name of data file: ";
10     cin.getline(filename, 60);
11     inFile.open(filename);
12     if (!inFile.is_open())
13     {
14         cout << "Could not open the file " << filename << endl;
15         cout << "Program terminatinf.\n";
16         exit(EXIT_FAILURE);
17     }
18     char value;
19     int count = 0;
20     inFile >> value;
21     while (inFile.good())
22     {
23         count++;
24         cout << value;
25         inFile >> value;
26     }
27     cout << endl;
28     if (inFile.eof())
29         cout << "End of file reached.\n";
30     else if (inFile.fail())
31         cout << "Input terminated by data mis match.\n";
32     else
33         cout << "Input terminated for unknown reason.\n";
34     if (count == 0)
35         cout << "No data processed.\n";
36     else
37     {
38         cout << "This file has " << count << " characters." << endl;
39     }
40     system("pause");
41     return 0;
42 }

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

4

Sam Stone

2000

Freida Flass

100500

Tammy Tubbs

5000

Rich Raptor

55000

 1 #include<iostream>
 2 #include<fstream>
 3 #include<string>
 4 using namespace std;
 5 
 6 struct stream
 7 {
 8     string name;
 9     double donation;
10 };
11 
12 int main()
13 {
14     ifstream inFile;   //声明ifstream对象
15     inFile.open("haha.txt");  //关联文件
16     if (!inFile.is_open())    //文件打开失败
17     {
18         cout << "Could not open the file "  << endl;
19         cout << "Program terminatinf.\n";
20         exit(EXIT_FAILURE);
21     }
22     int n, i, flag = 0;    //flag是决定是否打印None的标志
23     inFile >> n;
24     inFile.get();      //抵消换行
25     stream *str = new stream[n];
26     for (i = 0; i < n;i++)
27     {
28         getline(inFile, str[i].name);
29         inFile >> str[i].donation;
30         inFile.get();   //抵消换行
31     }
32     cout << "Grand Patrons:" << endl;
33     for (i = 0; i < n; i++)
34     {
35         if (str[i].donation>10000)
36         {
37             cout << str[i].name << "\t" << str[i].donation << endl;
38             flag = 1;
39         }
40     }
41     cout << endl;
42     if (flag == 0)
43         cout << "None" << endl;
44     cout << "Other Patrons:" << endl;
45     for (i = 0; i < n; i++)
46     {
47         if (str[i].donation<=10000)
48         {
49             cout << str[i].name << "\t" << str[i].donation << endl;
50             flag = 1;
51         }
52     }
53     cout << endl;
54     if (flag == 0)
55         cout << "None" << endl;
56     
57     inFile.close();   //使用完该文件记得close
58     delete[]str;      //用完new记得delete
59 
60     system("pause");
61     return 0;
62 }

注:一开始写的时候忘记两个inFile.get(),导致两个结果都是None,找终止循环的原因,可在循环后添加:

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;

猜你喜欢

转载自www.cnblogs.com/Fionaaa/p/12297015.html
今日推荐