C++ Primier Plus(第六版) 第六章 分支语句和逻辑运算符编程练习答案
- 1. 编写一个程序,读取键盘输入,知道遇到@符号位置,并回显输入(数字除外),同时将大写字符转换为小写,小写字符转换为大写(别忘了cctype函数系列)。
- 2. 编写一个程序,最多将10个donation值读到一个double数组中(如果您愿意,也可以使用类array)。程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。
- 3. 编写一个菜单裙动程序的雏形。该程序显示一个提供4个选项的菜单——每个选项用一个字母标记,如果用户使用有效选项之外的字母进行响应,程序将提示用户输入一个有效的字母,知道用户这样做为止。然后,该程序使用一条switch语句,根据用户的选择执行一个简单操作。该程序的运行情况如下:
- 4. 加入Benevolent Order of Programmer后,在BOP大会上,人们便可以通过加入者的真实姓名、头衔或者秘密BOP姓名来了解他(她)。请编写一个程序,可以使用真实姓名、头衔、秘密姓名或成员偏好来列出成员。编写该程序,请使用下面的结构:
- 5. 在Neutronia王国,货币单位是tvarp,收入所得税计算方式如下:
- 6. 编写一个程序,记录捐助给“维护合法权利团体”的资金。该程序要求用户输入捐献者数目,然后要求用户输入每一个捐献者的姓名和款项。这些信息被储存在一个动态分配的结构数组中,每个结构有两个成员:用来存储姓名的字符数组(或string对象)和用来存储款项的double成员。读取所有数据后,程序将显示所有捐款超过10000的捐款者的姓名及捐款数额。该列表前应包含一个标题,指出下面的捐款者是重要捐款人(Grand Partons)。然后,程序将列出其他的捐款者,该列表要以Partons开头。如果某种类别没有捐款者,程序将打印单词"none"。该程序只显示两种类别,而不进行排序。
- 7. 编写一个程序,它每次读取一个单词,直到用户只输入q。然后,该程序指出有多少个单词以元音打头,有多少个单词以辅音打头,还有多少个单词不属于这两类。为此,方法之一是,使用isalpha()来区分以字母和其他字符打头的单词,然后对于通过了isalpha()测试的单词,使用if或switch语句来确定哪些以元音打头。该程序的运行情况如下:
- 8. 编写一个程序,它打开一个文件,逐个字符的读取该文件,直到到达文件末尾,然后指出该文件中包含多少个字符。
- 9. 完成编程练习6,但从文件中读取所需的信息。该文件的第一项应为捐款人数,余下的内容英文成对的行。在每一对中,第一行为捐款人姓名,第二行为捐款数额。即该文件类似于下面:
1. 编写一个程序,读取键盘输入,知道遇到@符号位置,并回显输入(数字除外),同时将大写字符转换为小写,小写字符转换为大写(别忘了cctype函数系列)。
本题第一步,识别输入,遇到@停止,这里使用while(ch!='@')
判断数字用isdigit()函数,具体实现时错误用了break打破了循环(用于退出),应该用continue,打破本次循环,继续下一次循环。
判断大写字符islower()函数,转换可以用toupper函数
判断小写字符isupper()函数
代码如下:
// ex1.cpp -- read the key input #include<iostream> #include<cctype> int main() { using namespace std; char ch; cout << "Enter the text, type @ to terminate.\n"; ch = cin.get(); while(ch != '@') { if(isdigit(ch)) { ch = cin.get(); continue; //is continue not break } else if(islower(ch)) cout << char(toupper(ch)); else if(isupper(ch)) cout << char(ch + 32); else cout << ch; ch = cin.get(); } return 0; }
运行结果如下:
2. 编写一个程序,最多将10个donation值读到一个double数组中(如果您愿意,也可以使用类array)。程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。
本题首先定义一个double型数组变量用于存储,定义一个count计算输如值的数量;
使用while循环来实现输入:
while的调节语句根据 cin >> double的返回值类型来判断是否执行循环。
利用if break;来使输入10个变量后跳出循环。
代码如下:
// ex2.cpp -- calculate avergage #include<iostream> const int Max = 10; int main () { using namespace std; int count = 0; double donation[Max]; double sum = 0, average; int cnt_ab = 0; cout << "Enter the donation value, type char to terminate.\n"; cout << "Value #" << count + 1 << ": "; // get value while (cin >> donation[count]) { sum += donation[count];// calculate sum if(++count < Max) //v1: ++count <= Max { cout << "Value #" << count + 1 << ": "; } else break; } // average = sum / count; cout << "The average of " << count << " value is " << average << endl; for(int i = 0; i < count; i++) { if(donation[i] > average) cnt_ab++; } cout << "The number of value over average is " << cnt_ab << endl; return 0; }
运行结果如下:
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.
本题是编写一个菜单驱动程序的模型。首先声明一个showmenu的函数,接着开始进入主体部分,显示菜单,通过while()循环读取键入值,利用switch选择对应菜单选项。
代码如下:
// ex3.cpp -- write a model of memu #include<iostream> using namespace std; void showmenu(); int main() { char ch; showmenu(); cout << "please enter a c, p, t, or g: "; cin >> ch; while(ch != 'f') { switch(ch) { case 'c': case 'C': cout << "It's a carnivore.\n"; break; case 'p': case 'P': cout << "He is a pianist.\n"; break; case 't': case 'T': cout << "A maple is a tree.\n"; break; case 'g': case 'G': cout << "The game is funning.\n"; break; default : cout << "Please enter a correct char.\n";break; } cout << "please enter a c, p, t, or g: "; cin >> ch; // first forget to wirte } } void showmenu() { cout << "Please enter one of the following choices:\n" "c) carnivore p)pianist\n" "t) tree g)game\n" "f\n"; }
运行结果如下:
4. 加入Benevolent Order of Programmer后,在BOP大会上,人们便可以通过加入者的真实姓名、头衔或者秘密BOP姓名来了解他(她)。请编写一个程序,可以使用真实姓名、头衔、秘密姓名或成员偏好来列出成员。编写该程序,请使用下面的结构:
//Benevolent Order of Programmers name structure
struct bop{
char fullname[strsize];//real name
char title[strsize];
char bopname[strsize];
int preference;
};
该程序创建一个由上述结构组成的小型数组,并将其初始化为适当的值。另外,该程序使用一个循环,让用户在下面的选项中进行选择:
a. display by name b. display by title
c. display by bop name d. display by preference
q. quit
注意,"display by preference"并不意味者显示成员的偏好,而是意味着根据成员的偏好来列出成员。例如,如果偏好号为1,则选择d将显示程序员的头衔。该程序的运行情况如下:
Benevolent Order of Programmers Report
a. display by name b. display by title
c. display by bop name 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!
本题考查的是结构体数组的定义和初始化,在定义中,使用动态数组的话,应该先用new创建好,在依次添加,这样会比较麻烦。接着考查while和case的用法。题目中的四个显示选项利用显示函数来实现。
注:写显示函数时名称写错,导致编译一直失败。
代码如下:
// ex4.cpp -- using #include<iostream> using namespace std; const int strsize = 30; const int Arrsize = 5; struct bop{ char fullname[strsize];//real name char title[strsize]; char bopname[strsize]; int preference; }; const bop arrbop[Arrsize] //how to use bop * { {"Wimp Macho", "Beginner Programmer", "WMU", 0}, {"Raki Rhodes", "Junior Programmer", "RRA", 1}, {"Celia Laiter", "Beginner Programmer", "MIPS", 2}, {"Hoppy Hipman", "Analyst Trainee", "HHP", 1}, {"Pat Hand", "Junior Programmer", "LOOPY",2} }; void show_choice(); void disp_name(); void disp_title(); void disp_bopname(); void disp_perference(); int main() { // init bop char ch; show_choice(); cout << "Enter your choice: "; cin >> ch; while(ch != 'q') { switch(ch) { case 'a': disp_name(); break; case 'b': disp_title(); break; case 'c': disp_bopname(); break; case 'd': disp_perference();break; default : cout << "Please enter correct char.\n";break; } cout << "Next choice: "; cin >> ch; } cout << "Bye!\n"; return 0; } void show_choice() { cout << "Benevolent Order of Programmers Report\n" "a. display by name b. display by title\n" "c. display by bop name d. display by preference\n" "q. quit\n"; } void disp_name() { for(int i = 0; i < Arrsize; i++) cout << arrbop[i].fullname << endl; } void disp_title() { for(int i = 0; i < Arrsize; i++) cout << arrbop[i].title << endl; } void disp_bopname() { for(int i = 0; i < Arrsize; i++) cout << arrbop[i].bopname << endl; } void disp_perference() // function name wirte correct { for(int i = 0; i < Arrsize; i++) switch(arrbop[i].preference) { case 0 : cout << arrbop[i].fullname << endl;break; case 1 : cout << arrbop[i].title << endl;break; case 2 : cout << arrbop[i].bopname << endl;break; default: break; } }
运行结果如下:
5. 在Neutronia王国,货币单位是tvarp,收入所得税计算方式如下:
5000tvarps: 不收税
5001~15000tvarps: 10%
15001~35000tvarps: 15%
35000tvarps: 20%
例如,收入为38000tvarp时,所得税为5000 x 0.00 + 10000 x 0.10 + 20000 x 0.15 + 3000 x 0.20,即4600 tvarps。请编写一个程序,使用循环来要求用户输入收入,并报告所得税。当用户输入负数或非数字时,循环将结束。
本题首先编写一个计算所得税的函数,cal_tax();
利用if elseif将收入income分为不同的范围。分别代入公式计算。
在编写程序时,笔者将税率和范围分别存入了两个数组,这样方便以后修改参数。
代码如下:
// ex5.cpp -- calculating income tax #include<iostream> // tax rate const double rate[4] = {0, 0.10, 0.15, 0.20}; const double tax_p[3]= {5000, 15000, 35000}; double cal_tax(double income); int main() { using namespace std; double income, tax; cout << "Enter your income, you can get your income tax.\n" "type negative digits or no-numbers to terminate.\n"; cout << "Enter your income: "; while((income >= 0) && (cin >> income)) { tax = cal_tax(income); cout << "The tax of " << income << " tvarps is " << tax << " tvarps.\n"; cout << "Enter next income: "; } cout << "Bye!\n"; return 0; } double cal_tax(double income) { double tax; if(income <= tax_p[0]) tax = income * rate[0]; else if(income > tax_p[0] && income <= tax_p[1]) tax = (income - tax_p[0]) * rate[1]; else if(income > tax_p[1] && income <= tax_p[2]) tax = (income - tax_p[1]) * rate [2] + (tax_p[1] - tax_p[0]) * rate[1]; else if(income > tax_p[2]) tax = (tax_p[1] - tax_p[0]) * rate[1] + (tax_p[2] - tax_p[1]) * rate[2] + (income - tax_p[2]) * rate[3]; return tax; }
运行结果如下:
6. 编写一个程序,记录捐助给“维护合法权利团体”的资金。该程序要求用户输入捐献者数目,然后要求用户输入每一个捐献者的姓名和款项。这些信息被储存在一个动态分配的结构数组中,每个结构有两个成员:用来存储姓名的字符数组(或string对象)和用来存储款项的double成员。读取所有数据后,程序将显示所有捐款超过10000的捐款者的姓名及捐款数额。该列表前应包含一个标题,指出下面的捐款者是重要捐款人(Grand Partons)。然后,程序将列出其他的捐款者,该列表要以Partons开头。如果某种类别没有捐款者,程序将打印单词"none"。该程序只显示两种类别,而不进行排序。
本题考查了动态结构数组的输入,声明和输出,刚开始没有看清楚,以为要自动统计输入的个数,因此程序编写不顺利,后面仔细读题之后发现是输入已知个数的数据,声明动态结构数组时也出现了错误,
Parton* partons = new Parton[num]
;忘了声明数量num,导致输入时,大于3个元素无法读取。
计数输出"none"的程序刚开始位置错了,在循环里,导致输出多个"none"。
代码如下:
// ex6.cpp -- record the Patrons #include<iostream> #include<cstring> struct Patron { char name[20]; int donation ; }; int main() { using namespace std; int num; int count = 0; cout << "Please enter the number of patrons: "; (cin >> num).get(); Patron* patrons = new Patron[num]; cout << "Please enter the patrons' name and donations,\n"; cout << "Enter the partons' name: "; for (int i = 0; i < num; i++) { cout << "Praton #" << i + 1 << ":\n"; cout << "Name: "; cin.getline(patrons[i].name,20); cout << "Donation: "; cin >> patrons[i].donation; cin.get(); } // display Grand Patrons cout << "Grand Patrons\n"; for (int i = 0; i < num; i++) { if(patrons[i].donation > 10000) { cout << "Name: " << patrons[i].name << ", donation: " << patrons[i].donation << endl; count++; } } if(count == 0) { cout << "none\n"; } count = 0; cout << "Patrons\n"; cout << "Name: "; for (int i = 0; i < num; i++) { if(patrons[i].donation <= 10000) { cout << patrons[i].name << " "; count++; } } if(count == 0) { cout << "none"; } return 0; }
运行结果如下:
7. 编写一个程序,它每次读取一个单词,直到用户只输入q。然后,该程序指出有多少个单词以元音打头,有多少个单词以辅音打头,还有多少个单词不属于这两类。为此,方法之一是,使用isalpha()来区分以字母和其他字符打头的单词,然后对于通过了isalpha()测试的单词,使用if或switch语句来确定哪些以元音打头。该程序的运行情况如下:
Enter words(q to quit):
The 12 awesome oxen ambled
quietly across 15 meters of lawn. q
5 words beginning with vowels
4 words beginning with consontants
2 others
本题首先使用while()循环来实现输入'q'退出,while(word != 'q');
使用isalpha()区分字母和字符,字符用swit()来选择出元音和辅音。
代码如下:
// ex7.cpp -- get the words class #include<iostream> #include<string> #include<cctype> int main() { using namespace std; string word; int cnt_vowel = 0; int cnt_consonants = 0; int cnt_others; cout << "Enter words(q to quit): \n"; cin >> word; while (word != "q") { if(isalpha(word[0])) { switch(word[0]) { case 'a' : case 'A' : case 'e' : case 'E' : case 'i' : case 'I' : case 'o' : case 'O' : case 'u' : case 'U' : ++cnt_vowel;break; default: ++ cnt_consonants;break; } } else ++cnt_others; cin >> word; } cout << cnt_vowel << " words beginning with vowels\n"; cout << cnt_consonants << " words beginning with consonants\n"; cout << cnt_others << " others\n"; return 0; }
运行结果如下:
8. 编写一个程序,它打开一个文件,逐个字符的读取该文件,直到到达文件末尾,然后指出该文件中包含多少个字符。
本题考查的是文件的读取,要求逐个字符的读取。首先应该添加fstream头文件,然后有ifstream类创建一个对象inFile,在读取时,使用inFile.get()读取,这样可以读取空格换行制表符等字符。同时也会将这些字符统计上,要想不统计,可以使用if()函数。
在输入文件名时采用的时绝对路径,要想只输入文件名读取文件需要将文件与g++.exe放在同一个文件目录下。注:inFile.open()应与inFile.close()一起使用
代码如下:
// ex8.cpp -- read a file by char #include<iostream> #include<fstream> const int Fnsize = 40; int main() { using namespace std; ifstream inFile; char ch; int count = 0; char filename[Fnsize]; cout << "Enter the filename you want to open: \n"; cin.getline(filename, Fnsize); inFile.open(filename); inFile.get(ch); while(!inFile.eof()) { ++count; cout << ch; inFile.get(ch); // } inFile.close(); cout << "The file has " << count << " characters.\n"; return 0; }
运行结果如下:
9. 完成编程练习6,但从文件中读取所需的信息。该文件的第一项应为捐款人数,余下的内容英文成对的行。在每一对中,第一行为捐款人姓名,第二行为捐款数额。即该文件类似于下面:
4
Sam Stone
2000
Freida Flass
100500
Tammy Tubbs
5000
Rich Raptor
55000
本题考查了文件的按行读取,和数字字符串交替读取知识点。
文件按行读取,用ifstream类的getline()函数;读取数字时不会读取数字后面的换行符'\n',因此需要在读取数字后面加一个cin.get();或者 (inFile >> num).get()处理,笔者采用的第二种方法。
代码如下:
// ex9.cpp -- read file and deal with file #include<iostream> #include<cstring> #include<fstream> // const char filename[30] = "D:\\code\\C++\\chapter6\\patrons.txt"; struct Patron { char name[20]; int donation ; }; int main() { using namespace std; ifstream inFile; inFile.open("D:\\code\\C++\\chapter6\\patrons.txt"); int num; int count = 0; (inFile >> num).get(); Patron* patrons = new Patron[num]; for (int i = 0; i < num; i++) { inFile.getline(patrons[i].name,20); (inFile >> patrons[i].donation).get(); } inFile.close(); // display Grand Patrons cout << "Grand Patrons\n"; for (int i = 0; i < num; i++) { if(patrons[i].donation > 10000) { cout << "Name: " << patrons[i].name << ", donation: " << patrons[i].donation << endl; count++; } } if(count == 0) { cout << "none\n"; } //display Patrons count = 0; cout << "Patrons\n"; cout << "Name: "; for (int i = 0; i < num; i++) { if(patrons[i].donation <= 10000) { cout << patrons[i].name << " "; count++; } } if(count == 0) { cout << "none"; } return 0; }
运行结果如下:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程