面向对象的c++程序设计第六版课后习题答案第十章
- 格式:doc
- 大小:121.00 KB
- 文档页数:37
第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++程序设计课后答案编辑整理:尊敬的读者朋友们:这里是精品文档编辑中心,本文档内容是由我和我的同事精心编辑整理后发布的,发布之前我们对文中内容进行仔细校对,但是难免会有疏漏的地方,但是任然希望(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。
第一章:面向对象程序设计概述[1_1]什么是面向对象程序设计?面向对象程序设计是一种新型的程序设计范型。
这种范型的主要特征是:程序=对象+消息。
面向对象程序的基本元素是对象,面向对象程序的主要结构特点是:第一:程序一般由类的定义和类的使用两部分组成,在主程序中定义各对象并规定它们之间传递消息的规律。
第二:程序中的一切操作都是通过向对象发送消息来实现的,对象接受到消息后,启动有关方法完成相应的操作。
面向对象程序设计方法模拟人类习惯的解题方法,代表了计算机程序设计新颖的思维方式。
这种方法的提出是软件开发方法的一场革命,是目前解决软件开发面临困难的最有希望、最有前途的方法之一。
[1_2]什么是类?什么是对象?对象与类的关系是什么?在面向对象程序设计中,对象是描述其属性的数据以及对这些数据施加的一组操作封装在一起构成的统一体。
对象可以认为是:数据+操作在面向对象程序设计中,类就是具有相同的数据和相同的操作的一组对象的集合,也就是说,类是对具有相同数据结构和相同操作的一类对象的描述。
类和对象之间的关系是抽象和具体的关系。
类是多个对象进行综合抽象的结果,一个对象是类的一个实例。
在面向对象程序设计中,总是先声明类,再由类生成对象。
类是建立对象的“摸板”,按照这个摸板所建立的一个个具体的对象,就是类的实际例子,通常称为实例。
[1_3]现实世界中的对象有哪些特征?请举例说明。
对象是现实世界中的一个实体,其具有以下一些特征:(1)每一个对象必须有一个名字以区别于其他对象。
(2)需要用属性来描述它的某些特性。
(3)有一组操作,每一个操作决定了对象的一种行为。
(4)对象的操作可以分为两类:一类是自身所承受的操作,一类是施加于其他对象的操作。
例如:雇员刘名是一个对象对象名:刘名对象的属性:年龄:36 生日:1966.10.1 工资:2000 部门:人事部对象的操作:吃饭开车[1_4]什么是消息?消息具有什么性质?在面向对象程序设计中,一个对象向另一个对象发出的请求被称为“消息”。
第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++面向对象程序设计》习题答案(总29页)-CAL-FENGHAI.-(YICAI)-Company One1-CAL-本页仅作为文档封面,使用请直接删除《C++程序设计》习题解答目录第2部分习题解答................................................................................................... 错误!未定义书签。
第1章面向对象程序设计概述.................................. 错误!未定义书签。
第2章面向过程程序设计...................................... 错误!未定义书签。
第3章类和对象.............................................. 错误!未定义书签。
第4章继承与派生............................................ 错误!未定义书签。
第5章多态性与虚函数........................................ 错误!未定义书签。
第6章友元与静态成员........................................ 错误!未定义书签。
第7章运算符重载............................................ 错误!未定义书签。
第8章泛型编程.............................................. 错误!未定义书签。
第9章输入/输出............................................. 错误!未定义书签。
第10章异常处理............................................. 错误!未定义书签。
面向对象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语句,用来实现三路分支。
习题参考答案Chapter 11_1 对象客观世界中的事物都是对象,包括有形的物理对象,可感知的逻辑实体,以及概念化的抽象实体。
它有自己的属性,能够执行特定的操作。
类具有相同属性和操作的一组对象的集合;它描述的不是单个对象,而是“一类”对象的共同特征。
其重要性在于它是面向对象技术中最重要的结构,它支持信息隐藏和封装,进而支持对抽象数据类型(ADT)的实现。
1_2略1_3参考图如下图11_4 UML与面向对象UML是一种定义良好、易于表达、功能强大且普遍适用的建模语言。
它溶入了软件工程领域的新思想、新方法和新技术。
它的作用域不限于支持面向对象的分析与设计,还支持从需求分析开始的软件开发的全过程。
标准建模语言UML 适用于以面向对象技术来描述任何类型的系统,而且适用于系统开发的不同阶段,从需求规格描述直至系统完成后的测试和维护。
Chapter 22_1 程序的功能一般通过方法代码来实现。
每个方法都是从其第一行代码开始执行,直至最后一行代码结束,期间可以通过代码来调用其他的方法,从而完成各式各样的操作。
C#程序的起点是由Main方法定义的,程序总是从Main方法的第一行代码开始执行,在Main方法结束时停止运行。
2_2略(注:不同版本的V isual Studio的菜单项有所区别)2_3 略(注:不同版本的V isual Studio引用的程序集有所区别)2_4C#源代码会被编译为一种通用的中间语言(IL)代码,该语言类似于低级语言,但其代码与具体的硬件平台无关;之后CLR再针对特定的平台将IL程序翻译为机器指令,加载所需要的资源并管理执行。
2_5//动态链接库程序using System;namespace p2_5{class Adder{public static int Add(int a, int b){return a+b;}}}//控制台应用程序using System;using p2_5;namespace P2_6{class Program{static void Main(){Console.WriteLine("请输入两个数:");int a = int.Parse(Console.ReadLine());int b = int.Parse(Console.ReadLine());Console.WriteLine("{0}+{1}={2}", a, b, Adder.Add(a+b));}}}Chapter 33_1 略3_2第一:值类型的变量直接包含自身的所有数据,每创建一个变量,就在内存中开辟一块区域;只有通过变量才能修改它所包含的数据。
c++面向对象程序设计课后习题答案(谭浩强版)(总14页)页内文档均可自由编辑,此页仅为封面第一章5:#include <iostream> using namespace std;int main(){cout<<"This"<<"is";cout<<"a"<<"C++";cout<<"program."<<endl; return 0;}6:#include <iostream> using namespace std;int main(){int a,b,c;a=10;b=23;c=a+b;cout<<"a+b=";cout<<c;cout<<endl;return 0;}7:#include <iostream> using 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<<c<<endl;return 0;}int f(int x,int y,int z){int m;if (x<y) m=x;else m=y;if (z<m) m=z;return(m);}8: #include <iostream> using namespace std;int main(){int a,b,c;cin>>a>>b;c=a+b;cout<<"a+b="<<a+b<<endl; return 0;}9:#include <iostream>using namespace std;int main(){int add(int x,int y);int a,b,c;cin>>a>>b;c=add(a,b);cout<<"a+b="<<c<<endl; return 0;}int add(int x,int y){int c;c=x+y;return(c);}10:#include <iostream>using namespace std;int main(){void sort(int x,int y,int z); int x,y,z;cin>>x>>y>>z;sort(x,y,z);return 0;}void sort(int x, int y, int z){int temp;if (x>y) {temp=x;x=y;y=temp;} 2-4-12-4-22-5-12-5-2Box box1Box box1core; int k=0;for(int i=1;i<5;i++)if(arr[i].score>max_score) {max_score=arr[i].score;k=i;}cout<<arr[k].num<<" "<<max_score<<endl;}6:#include <iostream>using namespace std;class Student{public:Student(int n,float s):num(n),score(s){}void change(int n,float s) {num=n;score=s;}void display(){cout<<num<<" "<<score<<endl;}private:int num;float score;};int main(){Student stud(101,;();(101,;();return 0;}7: 解法一#include <iostream>using namespace std;class Student{public:Student(int n,float s):num(n),score(s){}void change(int n,float s) {num=n;score=s;}void display() {cout<<num<<" "<<score<<endl;}otal();Product::display();return 0;}10:#include <iostream>using namespace std;class Date;class Time{public:Time(int,int,int);friend void display(const Date &,const Time &); private:int hour;int minute;int sec;};Time::Time(int h,int m,int s){hour=h;minute=m;sec=s;}class Date{public:Date(int,int,int);friend void display(const Date &,const Time &); private:int month;int day;int year;};Date::Date(int m,int d,int y){month=m;day=d;year=y;}void display(const Date &d,const Time &t){cout<<<<"/"<<<<"/"<<<<endl;cout<<<<":"<<<<":"<<<<endl;int main(){Time t1(10,13,56);Date d1(12,25,2004);display(d1,t1);return 0;}11:#include <iostream>using namespace std;class Time;class Date{public:Date(int,int,int);friend Time;private:int month;int day;int year;};Date::Date(int m,int d,int y):month(m),day(d),year(y){ } class Time{public:Time(int,int,int);void display(const Date &);private:int hour;int minute;int sec;};Time::Time(int h,int m,int s):hour(h),minute(m),sec(s){ } void Time::display(const Date &d){cout<<<<"/"<<<<"/"<<<<endl;cout<<hour<<":"<<minute<<":"<<sec<<endl;}int main(){Time t1(10,13,56);Date d1(12,25,2004);(d1);return 0;}12:#include <iostream>using namespace std;template<class numtype>class Compare{public:Compare(numtype a,numtype b);numtype max();numtype min();private:numtype x,y;};template <class numtype>Compare<numtype>::Compare(numtype a,numtype b){x=a;y=b;}template <class numtype>numtype Compare<numtype>::max(){return (x>y)x:y;}template <class numtype>numtype Compare<numtype>::min(){return (x<y)x:y;}int main(){Compare<int> cmp1(3,7);cout<<()<<" is the Maximum of two integer numbers."<<endl;cout<<()<<" is the Minimum of two integer numbers."<<endl<<endl; Compare<float> cmp2,;cout<<()<<" is the Maximum of two float numbers."<<endl;cout<<()<<" is the Minimum of two float numbers."<<endl<<endl; Compare<char> cmp3('a','A');cout<<()<<" is the Maximum of two characters."<<endl;cout<<()<<" is the Minimum of two characters."<<endl;return 0;}第四章1:#include <iostream>using namespace std;class Complex{public:Complex(){real=0;imag=0;}Complex(double r,double i){real=r;imag=i;}double get_real();double get_imag();void display();private:double real;double imag;};double Complex::get_real(){return real;}double Complex::get_imag(){return imag;}void Complex::display(){cout<<"("<<real<<","<<imag<<"i)"<<endl;} Complex operator + (Complex &c1,Complex &c2) {return Complex()+(),()+());}int main(){Complex c1(3,4),c2(5,-10),c3;c3=c1+c2;cout<<"c3=";();return 0;}2:#include <iostream>using namespace std;class Complex{public:Complex(){real=0;imag=0;}Complex(double r,double i){real=r;imag=i;} Complex operator+(Complex &c2);Complex operator-(Complex &c2);Complex operator*(Complex &c2);Complex operator/(Complex &c2);void display();private:double real;double imag;};Complex Complex::operator+(Complex &c2) {Complex c;=real+;=imag+;return c;}Complex Complex::operator-(Complex &c2) {Complex c;=;=;return c;}Complex Complex::operator*(Complex &c2) {Complex c;=real**;=imag*+real*;return c;}Complex Complex::operator/(Complex &c2) {Complex c;=(real*+imag*/*+*;=(imag**/*+*;return c;}void Complex::display(){cout<<"("<<real<<","<<imag<<"i)"<<endl;} int main(){Complex c1(3,4),c2(5,-10),c3;c3=c1+c2;cout<<"c1+c2=";();c3=c1-c2;cout<<"c1-c2=";();c3=c1*c2;cout<<"c1*c2=";();c3=c1/c2;cout<<"c1/c2=";();return 0;}3:#include <iostream> ,"president","135 Beijing Road,Shanghai","(021)",;( );return 0;}10:#include <iostream>#include <cstring>using namespace std;class Teacher um<<" "<<staf[i].name<<" "<<staf[i].age<<""<<staf[i].pay<<endl;((char *)&staf[i],sizeof(staf[i]));}cout<<"please input data you want insert:"<<endl;for(i=0;i<2;i++){cin>>>>>>>>;(0,ios::end);((char *)&staf1,sizeof(staf1));}(0,ios::beg);for(i=0;i<7;i++){((char *)&staf[i],sizeof(staf[i]));cout<<staf[i].num<<" "<<staf[i].name<<" "<<staf[i].age<<" "<<staf[i].pay<<endl; }bool find;cout<<"enter number you want search,enter 0 to stop.";cin>>num;while(num){find=false;(0,ios::beg);for(i=0;i<7;i++){((char *)&staf[i],sizeof(staf[i]));if(num==staf[i].num){m=();cout<<num<<" is No."<<m/sizeof(staf1)<<endl;cout<<staf[i].num<<" "<<staf[i].name<<" "<<staf[i].age<<" "<<staf[i].pay<<endl; find=true;break;}}if(!find)cout<<"can't find "<<num<<endl;cout<<"enter number you want search,enter 0 to stop.";cin>>num;}();return 0;}6:解法一#include <iostream>#include <strstream>using namespace std;struct student{int num;char name[20];double score;};int main(){student stud[3]={1001,"Li",78,1002,"Wang",,1004,"Fun",90},stud1[3];char c[50];int i;ostrstream strout(c,50);for(i=0;i<3;i++)strout<<stud[i].num<<" "<<stud[i].name<<" "<<stud[i].score<<" ";strout<<ends;cout<<"array c:"<<endl<<c<<endl<<endl;istrstream strin(c,50);for(i=0;i<3;i++)strin>>stud1[i].num>>stud1[i].name>>stud1[i].score;cout<<"data from array c to array stud1:"<<endl;for(i=0;i<3;i++)cout<<stud1[i].num<<" "<<stud1[i].name<<" "<<stud1[i].score<<endl;cout<<endl;return 0;}6:解法二#include <iostream>#include <strstream>using namespace std;struct student{int num;char name[20];double score;};int main(){int i;student stud[3]={1001,"Li",78,1002,"Wang",,1004,"Fun",90},stud1[3]; char c[50];strstream strio(c,50,ios::in|ios::out);for(i=0;i<3;i++)strio<<stud[i].num<<" "<<stud[i].name<<" "<<stud[i].score<<" ";strio<<ends;cout<<"array c:"<<endl<<c<<endl<<endl;for(i=0;i<3;i++)strio>>stud1[i].num>>stud1[i].name>>stud1[i].score;cout<<"data from array c to array stud1:"<<endl;for(i=0;i<3;i++)cout<<stud1[i].num<<" "<<stud1[i].name<<" "<<stud1[i].score<<endl; cout<<endl;return 0;}第八章1:#include <iostream>#include <cmath>using namespace std;double q(double,double,double);void main(){double a,b,c,p,x1,x2;cout<<"please enter a,b,c:";cin>>a>>b>>c;p=-b/(2*a);try{x1=p+q(a,b,c);x2=p-q(a,b,c);cout<<"x1="<<x1<<endl<<"x2="<<x2<<endl;}catch(double d){cout<<"a="<<a<<",b="<<b<<",c="<<c<<",disc="<<d<<",error!"<<endl;} cout<<"end"<<endl;}double q(double a,double b,double c){double disc;disc=b*b-4*a*c;if (disc<0) throw disc;return sqrt(disc)/(2*a);}2:#include <iostream>#include <string>using namespace std;class Student{public:Student(int n,string nam){cout<<"constructor-"<<n<<endl;num=n;name=nam;}~Student(){cout<<"destructor-"<<num<<endl;}void get_data();private:int num;string name;};void Student::get_data(){if(num==0) throw num;else cout<<num<<" "<<name<<endl;cout<<"in get_data()"<<endl;}void fun(){Student stud1(1101,"tan");();try{Student stud2(0,"Li");();}catch(int n){cout<<"num="<<n<<",error!"<<endl;}}int main(){cout<<"main begin"<<endl;cout<<"call fun()"<<endl;fun();cout<<"main end"<<endl;return 0;}3://main file#include <iostream>using namespace std;#include ""#include ""using namespace std;using namespace student1;int main(){Student stud1(1001,"Wang",18,"123 Beijing Road,Shanghua"); ();student2::Student stud2(1102,"Li",'f',;();return 0;}//,文件名为#include <string>namespace student1{class Student{public:Student(int n,string nam,int a,string addr){num=n;name=nam;age=a;address=addr;}void show_data();private:int num;string name;int age;string address;};void Student::show_data(){cout<<"num:"<<num<<" name:"<<name<<" age:"<<age<<" address:"<<address<<endl;}}//,文件名为#include <string>namespace student2{class Student{public:Student(int n,string nam,char s,float sco){num=n;name=nam;sex=s;score=sco;}void show_data();private:int num;string name;char sex;float score;};void Student::show_data(){cout<<"num:"<<num<<" name:"<<name<<" sex:"<<sex <<" score:"<<score<<endl; }}。