面向对象的c++程序设计第六版课后习题答案第十章
C++第10章习题参考答案

四、综合题3 综合题3
答案: 答案: 调用d.vf2() 是错误的:对象将直接调用本类函数,但是 是错误的:对象将直接调用本类函数,但是DD 调用 类的vf2 函数需要一个参数。 函数需要一个参数。 类的 调用dp->vf2() 是错误的:由于 是错误的:由于DD 类的 类的vf2 函数和基类 函数和基类vf2 调用 的参数不一致,虚函数关系不成立,调用将指向DD 类 的参数不一致,虚函数关系不成立,调用将指向 函数,仍然出现参数的不一致。 的vf2 函数,仍然出现参数的不一致。 这两个语句注释掉后,运行的结果是: 这两个语句注释掉后,运行的结果是: DD::vf1 被调用 BB::vf2 被调用 EE::vf4 被调用 EE::vf3 被调用 联编的方式分别是:动态联编、静态联编、动态联编、 联编的方式分别是:动态联编、静态联编、动态联编、动 态联编。 态联编。
四、综合题2 综合题2
class Circle : public Shape { public: public: Circle( int = 0, int = 0, double = 0.0 ); const; virtual double getArea() const; const; void print() const; private: private: x,y; int x,y; radius; double radius; }; class Rectangle : public Shape { public: public: Rectangle( int = 0, int = 0); virtual double getArea() const const; void print() const; private: private: int a,b; a,b; };
c--面向对象程序设计课后习题解答-谭浩强

第1章C++ 的初步知识1.请根据你的了解,叙述C++的特点。
C++对C有哪些发展?【解】略。
2.一个C++的程序是由哪几部分构成的?其中的每一部分起什么作用?【解】略。
3.从拿到一个任务到得到最终结果,一般要经过几个步骤?【解】略.4.请说明编辑、编译、连接的作用。
在编译后得到的目标文件为什么不能直接运行?【解】编译是以源程序文件为单位进行的,而一个完整的程序可能包含若干个程序文件,在分别对它们编译之后,得到若干个目标文件(后缀一般为.obj),然后要将它们连接为一个整体.此外,还需要与编译系统提供的标准库相连接,才能生成一个可执行文件(后缀为。
exe)。
不能直接运行后缀为。
obj的目标文件,只能运行后缀为。
exe的可执行文件.5.分析下面程序运行的结果。
#includeusing namespace std;int main({cout<<” This "<〈” is ";cout〈<” a "<<” C++”;cout〈〈”program。
” <〈 endl;return 0;}【解】输出的结果为Thisisa C++program。
6.分析下面程序运行的结果。
#includeusing namespace std;int main({int a,b,c;a=10;b=23;c=a+b;cout〈〈” a+b=”;cout<cout<return 0;}【解】前两个cout语句在输出数据后不换行,第3个cout语句输出一个换行,因此输出的结果为a+b=337.分析下面程序运行的结果.请先阅读程序写出程序运行时应输出的结果,然后上机运行程序,验证自己分析的结果是否正确.以下各题同。
#includeusing namespace std;int main({int a,b,c;int f(int x,int y,int z;cin〉>a〉〉b>>c;c=f(a,b,c;cout<}int f(int x,int y,int z{int m;if (xelse m=y;if (zreturn(m;}【解】程序的作用是:输入3个整数,然后输出其中值最小的数。
CC++程序设计课后答案(2021年整理精品文档)

CC++程序设计课后答案编辑整理:尊敬的读者朋友们:这里是精品文档编辑中心,本文档内容是由我和我的同事精心编辑整理后发布的,发布之前我们对文中内容进行仔细校对,但是难免会有疏漏的地方,但是任然希望(CC++程序设计课后答案)的内容能够给您的工作和学习带来便利。
同时也真诚的希望收到您的建议和反馈,这将是我们进步的源泉,前进的动力。
本文可编辑可修改,如果觉得对您有帮助请收藏以便随时查阅,最后祝您生活愉快业绩进步,以下为CC++程序设计课后答案的全部内容。
第一章一、选择题1.C/C++规定,在一个源程序中,main()函数的位置( )。
CA。
必须在最开始 B。
必须在最后C.可以任意D.必须在系统调用的库函数的后面2。
以下()是C/C++合法的标识符。
AA.char2B.@xC.intD.7Bw3。
下面的程序,对于输入:2 9 15,输出的结果是( )。
B#include"iostream.h"void main(){int a;float b;cout<<”input a,b:”<<end l;cin>〉a>>b;cout<<”a+b="〈<a+b<<endl;}A。
2 B.11 C。
26 D。
244。
在Visual C++中,打开一个项目只需要打开对应的项目工作区文件即可,项目工作区文件的扩展名为()。
CA.objB.dspC.dsw D。
cpp5.下面关于C语言与C++关系的说法中,( )是正确的。
DA。
C语言是C++的子集 B.C++对C语言进行了改进C。
C++和C语言都是面向对象的 D.C++继承了C语言的众多优点6。
设置一个断点的方法是将光标移到需要设置断点的行上,然后按( )键。
AA.F9 B。
F10 C。
F11 D。
F127.下面关于编译预处理命令的说法中,正确的是( )。
CA。
一条文件包含命令能包含多个文件B.文件包含命令不可以嵌套使用C。
面向对象程序设计C课后题答案

第一章:面向对象程序设计概述[1_1]什么是面向对象程序设计?面向对象程序设计是一种新型的程序设计范型。
这种范型的主要特征是:程序=对象+消息。
面向对象程序的基本元素是对象,面向对象程序的主要结构特点是:第一:程序一般由类的定义和类的使用两部分组成,在主程序中定义各对象并规定它们之间传递消息的规律。
第二:程序中的一切操作都是通过向对象发送消息来实现的,对象接受到消息后,启动有关方法完成相应的操作。
面向对象程序设计方法模拟人类习惯的解题方法,代表了计算机程序设计新颖的思维方式。
这种方法的提出是软件开发方法的一场革命,是目前解决软件开发面临困难的最有希望、最有前途的方法之一。
[1_2]什么是类?什么是对象?对象与类的关系是什么?在面向对象程序设计中,对象是描述其属性的数据以及对这些数据施加的一组操作封装在一起构成的统一体。
对象可以认为是:数据+操作在面向对象程序设计中,类就是具有相同的数据和相同的操作的一组对象的集合,也就是说,类是对具有相同数据结构和相同操作的一类对象的描述。
类和对象之间的关系是抽象和具体的关系。
类是多个对象进行综合抽象的结果,一个对象是类的一个实例。
在面向对象程序设计中,总是先声明类,再由类生成对象。
类是建立对象的“摸板”,按照这个摸板所建立的一个个具体的对象,就是类的实际例子,通常称为实例。
[1_3]现实世界中的对象有哪些特征?请举例说明。
对象是现实世界中的一个实体,其具有以下一些特征:(1)每一个对象必须有一个名字以区别于其他对象。
(2)需要用属性来描述它的某些特性。
(3)有一组操作,每一个操作决定了对象的一种行为。
(4)对象的操作可以分为两类:一类是自身所承受的操作,一类是施加于其他对象的操作。
例如:雇员刘名是一个对象对象名:刘名对象的属性:年龄:36 生日:1966.10.1 工资:2000 部门:人事部对象的操作:吃饭开车[1_4]什么是消息?消息具有什么性质?在面向对象程序设计中,一个对象向另一个对象发出的请求被称为“消息”。
C++ Primer Plus(第6版)中文版》编程练习答案第6-10章

第6章分支语句和逻辑运算符//ex6.1#include<iostream>#include<cctype>int main(){using namespace std;char ch;cin.get(ch);while (ch != '@'){if (!isdigit(ch)){if (isupper(ch))ch = tolower(ch);else if (islower(ch))ch = toupper(ch);cout << ch;}cin.get(ch);}return 0;}//ex6.2#include<iostream>const int Max = 10;int main(){using namespace std;double num[Max];int i = 0;cout << "Number 1: ";while (i < Max && cin >> num[i]){if (++i < Max)cout << "Number " << i+1 << ": ";}double total = 0.0;for (int j = 0; j < i; j++)total += num[j];double Average = total/i;cout << "Average = " << Average << endl;int q = 0;for (int j = 0; j < i; j++)if (num[j] > Average)q++;cout << q << " numbers > average.\n";return 0;}//ex6.3#include<iostream>int main(){using namespace std;char ch;cout << "Please enter one of the choice:\n"<< "c) carnivore p) pianist\n"<< "t) tree g) game\n";cin >> ch;while (ch != 'c' && ch != 'p' && ch != 't' && ch != 'g'){cout << "Please enter a c, p, t, or g: ";cin >> ch;}switch (ch){case'c' : cout << "A cat is a carnivore.\n";break;case'p' : cout << "Radu Lupu is a pianist.\n";break;case't' : cout << "A maple is a tree.\n";break;case'g' : cout << "Golf is a game.\n";break;default : cout << "The program shouldn't get here!\n";}return 0;}//ex6.4#include<iostream>const int strsize = 20;struct bop{char fullname[strsize];char title[strsize];char bopname[strsize];int preference;};int main(){using namespace std;bop member[5] = {{"Wimp Macho", "English Teacher", "DEMON", 0},{"Raki Rhodes", "Junior Programmer", "BOOM", 1},{"Celia Laiter", "Super Star", "MIPS", 2},{"Hoppy Hipman", "Analyst Trainee", "WATEE", 1},{"Pat Hand", "Police", "LOOPY", 2}};char ch;cout << "Benevolent Order of Programmers Report\n"<< "a. display by name b. display by title\n"<< "c. display by bopname d. display by preference\n"<< "q. quit\n";cout << "Enter your choice: ";while (cin >> ch && ch != 'q'){switch (ch){case'a': for (int i = 0; i < 5; i++)cout << member[i].fullname << endl;break;case'b': for (int i = 0; i < 5; i++)cout << member[i].title << endl;break;case'c': for (int i = 0; i < 5; i++)cout << member[i].bopname << endl;break;case'd': for (int i = 0; i < 5; i++){if (member[i].preference == 0)cout << member[i].fullname << endl;else if (member[i].preference == 1)cout << member[i].title << endl;elsecout << member[i].bopname << endl;}break;}cout << "Next choice: ";}cout << "Bye!" << endl;return 0;}//ex6.5#include<iostream>const double LEV1 = 5000;const double LEV2 = 15000;const double LEV3 = 35000;const double RATE1 = 0.10;const double RATE2 = 0.15;const double RATE3 = 0.20;int main(){using namespace std;double income, tax;cout << "Enter your annual income in tvarps: ";cin >> income;if (income <= LEV1)tax = 0;else if (income <= LEV2)tax = (income - LEV1) * RATE1;else if (income <= LEV3)tax = RATE1 * (LEV2 - LEV1) + RATE2 * (income - LEV2);elsetax = RATE1 * (LEV2 - LEV1) + RATE2 * (LEV3 - LEV2)+ RATE3 * (income - LEV3);cout << "You owe Neutronia " << tax << " tvarps in taxes.\n";return 0;}//ex6.6#include<iostream>#include<string>using namespace std;struct Patrons{string name;double money;};int main(){cout << "输入捐赠者的数目: ";int num;cin >> num;Patrons* ps = new Patrons[num];cout << "输入每一个捐赠者的姓名和款项:\n";for (int i=0; i<num; i++){cout << "输入第" << i+1 << "位姓名: ";cin >> ps[i].name;cout << "输入第" << i+1 << "位款项: ";cin >> ps[i].money;}cout << "Grand Patron\n";for (int i=0; i<num; i++){if (ps[i].money > 10000)cout << ps[i].name << endl;}cout << "\nPatron\n";for (int i=0; i<num; i++){if (ps[i].money <= 10000)cout << ps[i].name << endl;}return 0;}//ex6.7#include<iostream>#include<string>#include<cctype>int main(){using namespace std;string word;int vowel = 0;int consonant = 0;int other = 0;char ch;cout << "Enter words (q to quit):\n";cin >> word;while (word != "q"){ch = tolower(word[0]);if (isalpha(ch)){if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')vowel ++;elseconsonant ++;}elseother ++;cin >> word;}cout << vowel << " words beginning with vowel\n"<< consonant << " words beginning with consonants\n"<< other << " others\n";return 0;}//ex6.8#include<iostream>#include<fstream>#include<cstdlib>const int SIZE = 60;int main(){using namespace std;char filename[SIZE];ifstream inFile;cout << "Enter name of data file: ";cin.getline(filename, SIZE);inFile.open(filename);if (!inFile.is_open()){cout << "Could not open the file " << filename << endl;cout << "Program terminating.\n";exit(EXIT_FAILURE);}int count = 0;char ch;inFile >> ch;while (inFile.good()){count ++;inFile >> ch; // get next value}cout << count << " characters in " << filename << endl;inFile.close(); // finished with the filereturn 0;}//ex6.9#include<iostream>#include<string>#include<fstream>#include<cstdlib>const int SIZE = 60;using namespace std;struct Patrons{string name;double money;};int main(){char filename[SIZE];ifstream inFile;cout << "Enter name of data file: ";cin.getline(filename, SIZE);inFile.open(filename);if (!inFile.is_open()){cout << "Could not open the file " << filename << endl;cout << "Program terminating.\n";exit(EXIT_FAILURE);}int num;inFile >> num;inFile.get();Patrons* ps = new Patrons[num];for (int i = 0; i<num; i++){getline(inFile, ps[i].name);inFile >> ps[i].money;inFile.get();}cout << "\nGrand Patrons:\n";int count1 = 0;for (int i = 0; i < num; i++){if (ps[i].money > 10000){cout << ps[i].name <<endl;count1++;}}if (count1 == 0)cout << "none";cout << "\nPatrons:\n";int count2 = 0;for (int i = 0; i < num; i++){if (ps[i].money <= 10000){cout << ps[i].name <<endl;count2++;}}if (count2 == 0)cout << "none";delete [] ps;inFile.close();return 0;}第7章函数——C++的编程模块//ex7.1#include<iostream>double t_av(double x, double y);int main(){using namespace std;double x, y;double result;cout << "Please enter two numbers (0 to stop): ";while ((cin >> x >> y) && x != 0 && y != 0){result = t_av(x, y);cout << "调和平均数 = " << result << endl;cout << "Please enter two numbers (0 to stop): ";}return 0;}double t_av(double x, double y){return 2.0 * x * y / (x + y);}//ex7.2#include<iostream>const int MAX = 10;using namespace std;int fill_ar(double ar[], int limit);void show_ar(const double ar[], int n);double average(const double ar[], int n);int main(){double scores[MAX];int size = fill_ar(scores, MAX);show_ar(scores, size);if (size > 0)cout << "The average of scores is: "<< average(scores, size) << endl;return 0;}int fill_ar(double ar[], int limit){double temp;int i;for (i = 0; i < limit; i++){cout << "Enter score #" << i+1 << ": ";cin >> temp;if (!cin){cin.clear();while (cin.get() != '\n')continue;cout << "Bad input; enter a number: ";break;}if (temp < 0)break;ar[i] = temp;}return i;}void show_ar(const double ar[], int n){for (int i = 0; i < n; i++)cout << "score #" << i+1 << ": " << ar[i] << endl; }double average(const double ar[], int n){double sum = 0.0;for (int i = 0; i < n; i++)sum += ar[i];return sum / n;}//ex7.3#include<iostream>struct box{char maker[40];float height;float width;float length;float volume;};void set_box(box *);void show_box(box);int main(){using namespace std;box carton = {"Bingo Boxer", 2, 3, 5};set_box(&carton);show_box(carton);return 0;}void set_box(box * pb){pb->volume = pb->height * pb->length * pb->width;}void show_box(box b){using namespace std;cout << "Box maker: " << b.maker<< "\nheight: " << b.height<< "\nlwidth: " << b.width<< "\nlength: " << b.length<< "\nvolume: " << b.volume << endl;}//ex7.4#include<iostream>long double probability(unsigned numbers, unsigned picks);int main(){using namespace std;double total, choices, mtotal;long double probability1, probability2;cout << "Enter total number of game card choices and\n""number of picks allowed for the field:\n";while ((cin >> total >> choices) && choices < total){cout << "Enter total number of game card choices and\n""number of picks allowed for the mega:\n";if (!(cin >> mtotal))break;probability1 = probability(total, choices);probability2 = probability(mtotal, 1);cout << "The chances of getting all "<< choices << " picks is one in "<< probability1 << ".\n";cout << "The chances of getting the megaspot is one in "<< probability2 << ".\n";cout << "You have one chance in ";cout << probability1 * probability2;cout << " of winning.\n";cout << "Next set of numbers (q to quit): ";}cout << "bye\n";return 0;}long double probability(unsigned numbers, unsigned picks){long double result = 1.0;long double n;unsigned p;for (n = numbers, p = picks; p > 0; n--, p--)result = result * n / p;return result;}//ex7.5#include<iostream>long long int recure(int);int main(){using namespace std;int number;cout << "Enter a integer (q to stop): ";while (cin >> number){long long int result = recure(number);cout << number << "! = " << result << endl;cout << "Next:";}cout << "Done!" << endl;return 0;}long long int recure(int n){long long int result;if (n > 0)result = n * recure(n-1);elseresult = 1;return result;}//ex7.6#include<iostream>const int Size = 10;int Fill_array(double ar[], int n);void Show_array(const double ar[], int n); void Reverse_array(double ar[], int n);int main(){using namespace std;double values[Size];int len = Fill_array(values, Size);cout << "Array values:\n";Show_array(values, len);cout << "Array reversed:\n";Reverse_array(values, len);Show_array(values, len);cout << "All but end values reversed:\n";Reverse_array(values+1, len-2);Show_array(values, len);return 0;}int Fill_array(double ar[], int n){using namespace std;double temp;int i;for (i=0; i<n; i++){cout << "Enter value #" << i+1 << ": ";cin >> temp;if (!cin)break;ar[i] = temp;}cout << endl;return i;}void Show_array(const double ar[], int n){using namespace std;for (int i=0; i<n; i++)cout << "Property #" << i+1 << ": "<< ar[i] << endl;cout << endl;}void Reverse_array(double ar[], int n){double temp;for (int i=0,j=n-1; i<j; i++,j--){temp = ar[i];ar[i] = ar[j];ar[j] = temp;}}//ex7.7#include<iostream>const int Max = 5;double * fill_array(double * begin, double * end);void show_array(const double * begin, const double * end); void revalue(double r, double * begin, double * end);int main(){using namespace std;double properties[Max];double * pbegin = properties;double * pend = fill_array(pbegin, pbegin + Max);show_array(pbegin, pend);if (pend-pbegin > 0){cout << "Enter revaluation factor: ";double factor;while (!(cin >> factor)){cin.clear();while (cin.get() != '\n')continue;cout << "Bad input; Please enter a number: ";}revalue(factor, pbegin, pend);show_array(pbegin, pend);}cout << "Done.\n";return 0;}double * fill_array(double * begin, double * end){using namespace std;double temp;int i = 1;while (begin < end){cout << "Enter value #" << i << ": ";cin >> temp;if (!cin){cin.clear();while (cin.get() != '\n')continue;cout << "Bad input; input process terminated.\n";break;}else if (temp < 0)break;*begin = temp;begin++;i++;}return begin;}void show_array(const double * begin, const double * end){using namespace std;int i = 1;while (begin < end){cout << "Property #" << i << ": $";cout << *begin << endl;begin++;i++;}}void revalue(double r, double * begin, double * end){while (begin < end){*begin *= r;begin++;}}//ex7.8a#include<iostream>const int Seasons = 4;const char * Snames[] = {"Spring", "Summer", "Fall", "Winter"}; void fill(double ar[], int n);void show(double ar[], int n);int main(){using namespace std;double expenses[Seasons];fill(expenses, Seasons);show(expenses, Seasons);return 0;}void fill(double ar[], int n){using namespace std;for (int i=0; i<n; i++){cout << "Enter " << Snames[i] << " expenses: ";cin >> ar[i];}}void show(double ar[], int n){using namespace std;cout << "\nEXPENSES\n";double total = 0.0;for (int i=0; i<n; i++){cout << Snames[i] << ": $" << ar[i] <<endl;total += ar[i];}cout << "Total Expenses: $" << total << endl;}//ex7.8b(传递结构值)#include<iostream>const int Seasons = 4;struct data{double arr[Seasons];};const char * Snames[] = {"Spring", "Summer", "Fall", "Winter"}; data fill();void show(data);int main(){using namespace std;data expenses = fill();show(expenses);return 0;}data fill(){using namespace std;data expenses;for (int i=0; i<Seasons; i++)cout << "Enter " << Snames[i] << " expenses: ";cin >> expenses.arr[i];}return expenses;}void show(data expenses){using namespace std;cout << "\nEXPENSES\n";double total = 0.0;for (int i=0; i<Seasons; i++){cout << Snames[i] << ": $" << expenses.arr[i] <<endl;total += expenses.arr[i];}cout << "Total Expenses: $" << total << endl;}//ex7.8b(传递结构指针)#include<iostream>const int Seasons = 4;struct data{double arr[Seasons];};const char * Snames[] = {"Spring", "Summer", "Fall", "Winter"}; void fill(data * pd);void show(data * pd);int main(){using namespace std;data expenses;fill(&expenses);show(&expenses);return 0;}void fill(data * pd){using namespace std;for (int i=0; i<Seasons; i++)cout << "Enter " << Snames[i] << " expenses: ";cin >> pd->arr[i];}}void show(data * pd){using namespace std;cout << "\nEXPENSES\n";double total = 0.0;for (int i=0; i<Seasons; i++){cout << Snames[i] << ": $" << pd->arr[i] <<endl;total += pd->arr[i];}cout << "Total Expenses: $" << total << endl;}//ex7.9#include<iostream>using namespace std;const int SLEN = 30;struct student {char fullname[SLEN];char hobby[SLEN];int ooplevel;};int getinfo(student pa[], int n);void display1(student st);void display2(const student * ps);void display3(const student pa[], int n);int main(){cout << "Enter class size: ";int class_size;cin >> class_size;while (cin.get() != '\n')continue;student * ptr_stu = new student[class_size];int entered = getinfo(ptr_stu, class_size);for (int i = 0; i < entered; i++)display1(ptr_stu[i]);display2(&ptr_stu[i]);}display3(ptr_stu, entered);delete [] ptr_stu;cout << "Done\n";return 0;}// getinfo() has two arguments: a pointer to the first element of // an array of student structures and an int representing the// number of elements of the array. The function solicits and// stores data about students. It terminates input upon filling// the array or upon encountering a blank line for the student// name. The function returns the actual number of array elements // filled.int getinfo(student pa[], int n){int num_array_elem = n;char tmp[SLEN];for (int i = 0; i < n; ++i){cout << "Enter name: ";cin.getline(tmp, SLEN);bool blank_line = true;for (unsigned j = 0; j < strlen(tmp); ++j){if (!isspace(tmp[j])){blank_line = false;break;}}if (blank_line){num_array_elem = i;break;}strcpy(pa[i].fullname, tmp);cout << "Enter hobby: ";cin.getline(pa[i].hobby, SLEN);cout << "Enter ooplevel: ";cin >> pa[i].ooplevel;cin.get();}cout << endl;return num_array_elem;}// display1() takes a student structure as an argument// and displays its contentsvoid display1(student st){cout << st.fullname << '\t'<< st.hobby << '\t'<< st.ooplevel << endl;}// display2() takes the address of student structure as an// argument and displays the structure’¡¥s contentsvoid display2(const student * ps){cout << ps->fullname << '\t'<< ps->hobby << '\t'<< ps->ooplevel << endl;}// display3() takes the address of the first element of an array// of student structures and the number of array elements as// arguments and displays the contents of the structuresvoid display3(const student pa[], int n){for (int i = 0; i < n; ++i)cout << pa[i].fullname << '\t' << pa[i].hobby << '\t' <<pa[i].ooplevel << endl;}//ex7.10#include<iostream>double calculate(double x, double y, double (*pf)(double, double)); double add(double x, double y);double sub(double x, double y);double mean(double x, double y);int main(){using namespace std;double a, b;double (*pf[3])(double, double) = {add, sub, mean};char * op[3] = {"add", "sub", "mean"};cout << "Enter pairs of numbers (q to quit): ";while (cin >> a >> b){for (int i=0; i<3; i++){cout << op[i] << ": " << a << " and " << b << " = "<< calculate(a, b, pf[i]) << endl;}}}double calculate(double x, double y, double (*pf)(double, double)) {return (*pf)(x, y);}double add(double x, double y){return x + y;}double sub(double x, double y){return x - y;}double mean(double x, double y){return (x + y) / 2.0;}第8章函数探幽//ex8.1#include<iostream>void show(const char * ps, int n = 0);int main(){using namespace std;char * pstr = "Hello\n";show(pstr);int num;cout << "Enter a number: ";cin >> num;show(pstr, num);cout << "Done\n";return 0;}void show(const char * ps, int n){using namespace std;int lim = n;if (n == 0)lim = 1;for (int i=0; i<lim; i++)cout << ps;}//ex8.2#include<iostream>#include<string>using namespace std;struct CandyBar{string name;double weight;int hot;};void set(CandyBar & cb, char * ps, double w, int h); void show(const CandyBar & cb);int main(){using namespace std;CandyBar candy;char * p = "Millennium Munch";double x = 2.85;int y = 350;set(candy, p, x, y);show(candy);return 0;}void set(CandyBar & cb, char * ps, double w, int h){ = ps;cb.weight = w;cb.hot = h;}void show(const CandyBar & cb){cout << "Name: " << << endl<< "Weight: " << cb.weight << endl<< "Hot: " << cb.hot << endl;}//ex8.3#include<iostream>#include<string>#include<cctype>using namespace std;void str_to_upper(string & str);int main(){string str1;cout << "Enter a string (q to quit): ";while (getline(cin, str1) && str1!="q" && str1!="Q") {str_to_upper(str1);cout << str1 << endl;cout << "Next string (q to quit): ";}cout << "Bye.";return 0;}void str_to_upper(string & str){int limit = str.size();for (int i=0; i<limit; i++){if (isalpha(str[i]))str[i] = toupper(str[i]);}}// ex8.4#include<iostream>#include<cstring>// for strlen(), strcpy()using namespace std;struct stringy {char * str; // points to a stringint ct; // length of string (not counting '\0')};void show(const char *str, int cnt = 1);void show(const stringy & bny, int cnt = 1);void set(stringy & bny, const char * str);int main(void){stringy beany;char testing[] = "Reality isn't what it used to be.";set(beany, testing); // first argument is a reference,// allocates space to hold copy of testing,// sets str member of beany to point to the// new block, copies testing to new block,// and sets ct member of beany show(beany); // prints member string onceshow(beany, 2); // prints member string twicetesting[0] = 'D';testing[1] = 'u';show(testing); // prints testing string onceshow(testing, 3); // prints testing string thriceshow("Done!");return 0;}void show(const char *str, int cnt){while(cnt-- > 0)cout << str << endl;}}void show(const stringy & bny, int cnt){while(cnt-- > 0){cout << bny.str << endl;}}void set(stringy & bny, const char * str){bny.ct = strlen(str);bny.str = new char[bny.ct+1];strcpy(bny.str, str);}//ex8.5#include<iostream>const int Limit = 5;template <typename T>T max5(T ar[]);int main(){using namespace std;int ari[Limit] = {1, 2, 3, 5, 4};double ard[Limit] = {1.1, 2.2, 3.3, 5.5, 4.4};int maxi = max5(ari);double maxd = max5(ard);cout << "maxi = " << maxi << endl;cout << "maxd = " << maxd << endl;return 0;}template <typename T>T max5(T ar[]){T max = ar[0];for (int i=1; i<Limit; i++)if (max < ar[i])max = ar[i];}return max;}//ex8.6#include<iostream>template <typename T>T maxn(T ar[], int n);template <> const char* maxn(const char* ar[], int n);int main(){using namespace std;int ari[6] = {1, 2, 3, 4, 6, 5};double ard[4] = {1.1, 2.2, 4.4, 3.3};const char * ars[5] = {"a","bb","ccc","ddddd","eeee"};cout << "The max integer of array is: " << maxn(ari, 6) << endl;cout << "The max double of array is: " << maxn(ard, 4) << endl;cout << "The max string of array is: " << maxn(ars, 5)<<endl; }template <typename T>T maxn(T ar[], int n){T maxar = ar[0];for (int i=1; i<n; i++){if (maxar < ar[i])maxar = ar[i];}return maxar;}template <> const char* maxn(const char* ar[],int n) {const char * maxs = ar[0];for (int i=1; i<n; i++){if (strlen(maxs) < strlen(ar[i]))maxs = ar[i];}return maxs;}//ex8.7#include<iostream>template <typename T>T SumArrray(T arr[], int n);template <typename T>T SumArrray(T * arr[], int n);struct debts{char name[50];double amount;};int main(){using namespace std;int things[6] = {13, 31, 103, 301, 310, 130};struct debts mr_E[3] ={{"Ima Wolfe", 2400.0},{"Ura Foxe", 1300.0},{"Iby Stout", 1800.0}};double * pd[3];for (int i=0; i<3; i++)pd[i] = &mr_E[i].amount;cout << "Sum: Mr.E's counts of things: "<< SumArrray(things, 6) << endl;cout << "Sum: Mr.E's debts: "<< SumArrray(pd, 3) << endl;return 0;。
面向对象程序设计课后答案(完整版)

第二章2-4#include <iostream>using namespace std;Add(int a,int b);int main(){int x,y,sum;cout<<"please input x and y:";cin>>x>>y;sum = add(x,y);cout <<x<<"+"<<y<<"="<<sum<<endl;}Add(int a,int b){return a+b;}2-5(1)this is a C++ program.(2)x=50.6 y=10 z=Ax=216.34 y=10 z=Ax=216.34 y=2 z=Ax=216.34 y=2 z=E(3)x y z500 1000 0500 1500 1500500 200 15002-6#include <iostream>using namespace std;int main(){int *p,*init;int countp=0;int countn=0;p = new int[20];init = p;for(int i=0;i<20;i++){cin>>*p;p++;}p = p-20;for( i=0;i<20;i++){if(*p>0) countp++;if(*p<0) countn++;cout<<*p<<" ";p++;}cout<<"正数有:"<<countp<<endl; cout<<"负数有:"<<countn<<endl;p = init;delete[] p;return 0;}2-7不做要求#include <iostream>//#include <string>using namespace std;void checkagescore(string name,int age) {if (name == "exit") throw name;if(age<0||age>50)throw age;int main(){string name;int age;for(int i=0 ;i<5 ;i++ ){cin.ignore ();getline(cin,name );cin>>age ;try{checkagescore(name,age);}catch( string){cout<<"exception :name is exit"<<endl;continue;}catch(int){cout<<"exception :age is not proper"<<endl;continue;}cout<<"name:"<<name<<" age :"<<age<<endl;}return 0;}第三章3-1(1)A (2)C (3)B (4)C (5)C(6)B (7)B (8)C (9)C3-7(1)main()函数中p1.age = 30;语句是错误的。
C++面向对象程序设计习题答案

《C++面向对象程序设计》习题答案(总29页)-CAL-FENGHAI.-(YICAI)-Company One1-CAL-本页仅作为文档封面,使用请直接删除《C++程序设计》习题解答目录第2部分习题解答................................................................................................... 错误!未定义书签。
第1章面向对象程序设计概述.................................. 错误!未定义书签。
第2章面向过程程序设计...................................... 错误!未定义书签。
第3章类和对象.............................................. 错误!未定义书签。
第4章继承与派生............................................ 错误!未定义书签。
第5章多态性与虚函数........................................ 错误!未定义书签。
第6章友元与静态成员........................................ 错误!未定义书签。
第7章运算符重载............................................ 错误!未定义书签。
第8章泛型编程.............................................. 错误!未定义书签。
第9章输入/输出............................................. 错误!未定义书签。
第10章异常处理............................................. 错误!未定义书签。
面向对象C++程序设计——各章习题答案

面向对象C++程序设计各章习题参考答案第1章面向对象技术概论一.选择题1. A2. C3. D4. B5. C二.填空题1. 封装、继承、多态性2. 面向对象分析(OOA)、面向对象设计(OOD)、面向对象实现(OOI)、面向对象测试(OOT)和面向对象系统维护(OOSM)。
3. 实例实例4. 多态性5. 消息消息传递第2章 C++简单程序设计一.选择题:1. B2. B3. B4. C5. C6. D7. D8. C9. D 10. C11. A 12. A二.填空题:1.4;2;2;8;12. 103. 04. 87;79;115. (1)x值为6,表达式的值为6(2)x值为6,但表达式的值为5(3)x值为4,表达式的值为4(4)x值为5,表达式的值为5(5)x变为6,y的值为5(6)x变为4,y的值为4(7)x变为6,y的值为25(8)x的值为6,y的值为366. const7. c+i*sizeof (c[i])8. x<=3||x>=109. a<=b&&b!=510. 30 30三.程序分析题:1.s=552.a,b99,96,194100.2,94.8,1963.i,s=15,564.13 15 22 14 645.14 25四.编程题(参考答案):1. 假设数组中含8个元素,参考答案如下:#include<iostream.h>void main(){int c=0,i,a[8],k;cout<<"input a[i]:"<<endl;for(i=0;i<8;i++)cin>>a[i];cout<<"input k:"<<endl;cin>>k;for (i=0;i<8;i++)if (a[i]>=k) c++;cout<<c;cout<<endl;}2. 参考答案:#include<iostream.h>void main(){const int n=50,m=10;int i,j,k;int index[n]; //存放学号float s,score[n],sum; //存放成绩for(i=0;i<n;i++)cin>>index[i]>>score[i]; //从键盘输入数据sum+=score[i];cout.precision(2); //设置输出宽度cout<<endl<<"A verage score:"<<sum/n; //输出平均分数cout.width(28); //设置输出宽度cout<<endl<<"Student ID:"; //输出学号for(i=0;i<10;i++) //选取前m名分数最高的学生,输出其学号及成绩{s=score[i];k=i;for(j=i+1;j<n;j++)if(s<score[j]){s=score[j];k=j;}if(k>i){score[k]=score[i];score[i]=s;j=index[k];index[k]=index[i];index[i]=j;}cout.width(4); //输出序号,学号和分数cout<<endl<<i+1;cout.width(11);cout<<index[i];cout.width(12);cout.precision(2);cout<<score[i];}cout<<endl;}3.#include<iostream.h>void main(){double x,y;cout<<”Input x:”;cin>>x;if(x<3.0)y=(x-2)*x;elseif(x>=-3.0&&x<=3.0) y=x;else y=x-2;cout<<”x=”<<x<<”,”<<”y=”<<y<<endl;}执行该程序后,显示如下信息:(分别输入3.2,2,-5) Input x:3.2↙输出结果如下:x=3.2,y=1.2Input x:2↙输出结果如下:x=2,y=2Input x:-5↙输出结果如下:x=-5,y=35该程序中使用了if-else if-else语句,用来实现三路分支。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
interest rate is a double (decimal) fraction rather
1. Class grading program
I have put statements of programming strategy and of the problem in the program comments.
One
struct StudentRecord
{
int studentNumber;
90 95
enter the student number: 2
enter two 10 point quizes
9 8
enter the midterm and final exam grades. These are 100 point tests
90 80
enter the student number: 3
double InitialBalance();
double BalanceAtMaturity();
int Term();
void input(istream&);
void output(ostream&);
private:
No Answer Provided
5. No Answer Provided
enter two 10 point quizes
7 8
enter the midterm and final exam grades. These are 100 point tests
70 80
enter the student number: 4
enter two 10 point quizes
5 4 0 40 35
Command line command to execute the text run:
ch10prg1 < data
Output:
enter the student number: 1
enter two 10 point quizes
7 10
enter the midterm and final exam grades. These are 100 point tr student number: 1
The quiz grades are: 7 10
The midterm and exam grades are: 90 95
The numeric average is:
and the letter grade assigned is A
Remark:The changes to be made are in the functions that take balance as argument. The implementation of the members must change:
1) to generate the int objects dollars and cents from the external representation of balance (a double)
<< "The numeric average is: " <<
<< endl
<< "and the letter grade assigned is "
<<
<< endl;
}
Data for the test run:
1 7 10 90 95
2 9 8 90 80
3 7 8 70 80
4 5 8 50 70
The record for student number: 4
The quiz grades are: 5 8
The midterm and exam grades are: 50 70
The numeric average is:
and the letter grade assigned is D
cin >> >> ;
cout << << " " <<
<< endl << endl;
}
void computeGrade(StudentRecord& student)
{
n";
abort();
}
= letterGrade[index];
}
void output(const StudentRecord student)
term is stored the same
#include <iostream>
using namespace std;
class CDAccount
{
public:
CDAccount();
CDAccount(double bal, double intRate, int T );
double InterestRate();
output function (ostream&);
Embed in a test program
The code in Display makes the behavior of the required functions clear.
Note on capitalization schemes:I use a slightly different capitalization scheme than the author. You should make your conventions clear to the student. Any capitalization that produces readable code is acceptable to this author. The instructor, as always, is left free to do as is wished.
{
cout << "The record for student number: "
<< << endl
<< "The quiz grades are: "
<< << " " <<
<< endl
<< "The midterm and exam grades are: "
<< << " " <<
<< endl
(uses 3 char args)
a constructor to set month base on month number, 1 = January etc.
a default constructor (what does it do?)
an input function to set the month based on the month number
void output(const StudentRecord student);
int main()
{
StudentRecord student[CLASS_SIZE];
for(int i = 0; i < CLASS_SIZE; i++)
input(student[i]);
<< "These are 100 point tests\n";
5 8
enter the midterm and final exam grades. These are 100 point tests
50 70
enter the student number: 5
enter two 10 point quizes
4 0
enter the midterm and final exam grades. These are 100 point tests
Chapter 10
DEFINING CLASSES AND ABSTRACT DATA TYPES
1. Solutions for and Remarks on Selected Programming Problems
This chapter can be done after Chapter7, Arrays. However, I have not used anything from that chapter in these solutions. Several of these solutions could be simplified in good measure if arrays were used instead of the extensive switch and nested if else statements.
CD account, different interface
Redo the definition of class CDAccount from Project 2 so that the interface is the same but the implementation is different. The new implementation is similar to the second implementation of BankAccount in Display . Here the balance is recorded in two int values, one for dollars, one for cents. The member variable for interest rate stores the interest as a fraction rather than a percentage. Term is stored as in Project 2.