C Primer Plus第6版中文版勘误表教学提纲

合集下载

C++ primer plus(第6版)中文版编程练习答案第10章

C++ primer plus(第6版)中文版编程练习答案第10章

第10章1、//Customs.h#include <stdio.h>#include <tchar.h>#include <string>#include <iostream>using namespace std;class Customs{private:string name;string accnum;double balance;public:Customs(const string &client, const string &num, double bal = 0.0);~Customs();void show()const;bool deposit(double cash);bool withdraw(double cash);};//Customs.cpp#include "Customs.h"Customs::Customs(const string &client,const string &num, double bal) {accnum = num;name = client;balance = bal;}Customs::~Customs(){}bool Customs::deposit(double cash){if (cash <= 0){cout << "Deposit must greater than zero\n";return false;}else{cout << "Custom deposits $" << cash << " dolars.\n";balance += cash;return true;}}bool Customs::withdraw(double cash){if (cash <= 0 || (balance - cash) < 0){cout << "Withdraw money error, must less than balance and greater than zero\n";return false;}else{cout << "Custom withdraws $" << cash << " dolars\n";balance -= cash;return true;}}void Customs::show()const{cout << "Account custom's name is " << name << endl;cout << "Account number is " << accnum << endl;cout << "Custom's balance is " << balance << endl;}//main.cpp#include "Customs.h"int main(){double input, output;char ch;Customs custom=Customs("Jacky","Jc",3000.32);custom.show();cout << "Please enter A to deposit balance ,\n"<< "P to withdraw balance, or Q to quit.: ";while (cin >> ch && toupper(ch)!='Q'){while (cin.get() != '\n')continue;if (!isalpha(ch)){cout << '\a';continue;}switch (ch){case'A':case'a':cout << "Enter a account number to deposit: ";cin >> input;if (!custom.deposit(input))cout << "Add error\n";elsecout << "Add success\n";break;case'P':case'p':cout << "Enter a account number to withdraw: ";cin >> output;if (!custom.withdraw(output))cout << "Withdraw error\n";elsecout << "Withdraw success\n";break;}custom.show();cout << "Please enter A to deposit balance ,\n"<< "P to withdraw balance, or Q to quit: ";}cout << "Bye\n";cin.get();cin.get();return 0;}2、//person.h#ifndef PERSON_H_#define PERSON_H_#include <iostream>#include <stdio.h>#include <tchar.h>#include <string>using namespace std;class Person{private:static const int Person::LIMIT = 25;string lname;char fname[LIMIT];public:Person(){ lname = ""; fname[0] = '\0'; }Person(const string &ln, const char *fn = "Heyyou");void Show()const;void FormalShow()const;};#endif//person.cpp#include "person.h"Person::Person(const string &ln, const char *fn){lname = ln;strncpy_s(fname, fn, LIMIT);fname[LIMIT] = '\0';}void Person::Show()const{cout << fname << " " << lname;}void Person::FormalShow()const{cout << lname << ", " << fname; }//usePerson.cpp#include "person.h"int main(){Person one;Person two("Smythecraft");Person three("Dimwiddy", "Sam");one.Show();cout << endl;one.FormalShow();cout << endl;two.Show();cout << endl;two.FormalShow();cout << endl;three.Show();cout << endl;three.FormalShow();cout << endl;cin.get();return 0;}3、//golf.h#ifndef GOLF_H_#define GOLF_H_#include <iostream>#include <string>using namespace std;class golf{private:static const int Len = 40;char fullname[Len];int handicap;public:golf();golf(const char *name, int hc = 0);golf(golf &g);~golf();void handicapf(int hc);void show()const;};#endif//golf.cpp#include "golf.h"golf::golf(){}golf::golf(const char *name, int hc){strncpy_s(fullname, name, Len);fullname[Len] = '\0';handicap = hc;}golf::golf(golf &g){strncpy_s(this->fullname, g.fullname, Len);this->handicap = g.handicap;}golf::~golf(){}void golf::handicapf( int hc){handicap = hc;}void golf::show()const{cout << fullname << ", " << handicap << endl; }//main.cpp#include "golf.h"int main(){char name[40] = "\0";int no;cout << "Enter a name: ";cin.getline(name, 40);cout << "Enter a level: ";cin >> no;golf ann(name, no);ann.show();golf andy = golf(ann);andy.show();cin.get();cin.get();return 0;}4、//Sales.h#ifndef SALE_H_#define SALE_H_#include <iostream>#include <string>using namespace std;namespace SALES{class Sales{private:static const int QUARTERS = 4;double sales[QUARTERS];double average;double max;double min;public:Sales();Sales(const double *ar);Sales(Sales &s);~Sales();void showSales()const;};}#endif//Sales.cpp#include "Sales.h"using namespace SALES;Sales::Sales(){sales[QUARTERS] = '\0';average = 0.0;max = 0.0;min = 0.0;}Sales::Sales(const double *ar){double sum=0.0;for (int i = 0; i < QUARTERS; i++){sales[i] = ar[i];sum += sales[i];}average = sum / QUARTERS;max = sales[0];for (int i = 0; i < QUARTERS-1; i++){if (sales[i] < sales[i + 1])max = sales[i + 1];}min = sales[0];for (int i = 0; i < QUARTERS-1; i++){if (sales[i] > sales[i + 1])min = sales[i + 1];}}Sales::Sales(Sales &s){for (int i = 0; i < QUARTERS; i++)this->sales[i] = s.sales[i];this->average = s.average;this->max = s.max;this->min = s.min;}Sales::~Sales(){}void Sales::showSales()const{cout << "The sales number is \n";for (int i = 0; i < QUARTERS; i++){cout << sales[i] << " ";}cout << endl;cout << "The sales average is " << average << endl;cout << "The sales max is " << max << endl;cout << "The sales min is " << min << endl;}//main.cpp#include "Sales.h"using namespace SALES;int main(){double nums[4];cout << "Please enter four numbers: \n";for (int i = 0; i < 4; i++)cin >> nums[i];Sales sn(nums);sn.showSales();Sales sn1(sn);sn1.showSales();cin.get();cin.get();return 0;}5、//stack.h#ifndef STACK_H_#define STACK_H_#include <iostream>#include <string>#include <stdio.h>using namespace std;struct customer{char fullname[35];double payment;};typedef struct customer Item;class Stack{private:enum{ MAX = 10 };Item items[MAX];double sum;int top;public:Stack();~Stack();bool isempty()const;bool isfull()const;bool push(const Item &item);bool pop(Item &item);};#endif#include "stack.h"Stack::Stack(){top = 0;sum = 0.0;}Stack::~Stack(){}bool Stack::isempty()const{return top == 0;}bool Stack::isfull()const{return top == MAX;}bool Stack::push(const Item &item) {if (top < MAX){items[top++] = item;return true;}elsereturn false;}bool Stack::pop(Item &item){if (top > 0){item = items[--top];sum += item.payment;cout << sum << endl;return true;}return false;}//main.cpp#include "stack.h"int main(){Stack st;char ch;Item cs;cout << "Please enter A to add a purchase order,\n"<< "P to process a PO, or Q to quit.\n";while (cin >> ch && toupper(ch) != 'Q'){while (cin.get() != '\n')continue;if (!isalpha(ch)){cout << '\a';continue;}switch (ch){case 'A':case 'a':cout << "Enter a PO number to add: ";cin >> cs.fullname;cin >> cs.payment;if (st.isfull())cout << "stack already full\n";elsest.push(cs);break;case 'P':case 'p':if (st.isempty())cout << "stack already empty\n";else{st.pop(cs);cout << "PO #" << cs.fullname << "popped\n";}break;}cout << "Please enter A to add a purchase order,\n"<< "P to process a PO, or Q to quit.\n";}cout << "Bye\n";cin.get();cin.get();return 0;}6、//Move.h#ifndef MOVE_H_#define MOVE_H_#include <stdio.h>#include <iostream>#include <string>using namespace std;class Move{private:double x;double y;public:Move(double a = 0, double b = 0);void showmove()const;Move add(const Move &m)const;void reset(double a = 0, double b = 0);};#endif//Move.cpp#include "Move.h"Move::Move(double a, double b){x = a;y = b;}void Move::showmove()const{cout << "x = " << x << endl;cout << "y = " << y << endl;}Move Move::add(const Move &m)const {Move xy_add;xy_add.x = m.x + this->x;xy_add.y = m.y + this->y;return xy_add;}void Move::reset(double a, double b) {x = a;y = b;}//main.cpp#include "Move.h"int main(){Move xy0(1, 1);xy0.showmove();Move xy1;xy1 = Move(2, 2);xy1.showmove();xy1 = xy1.add(xy0);xy1.showmove();xy1.reset(2.5, 2.5);xy1.showmove();cin.get();return 0;}7、//plorg.h#ifndef PLORG_H_#define PLORG_H_#include <iostream>#include <string>#include <stdio.h>using namespace std;class plorg{private:static const int len = 19;char fullname[len];int CI;public:plorg(const char *name = "Plorga", int ci = 50);~plorg();void p_fix(int ci);void show()const;};#endif//plorg.cpp#include "plorg.h"plorg::plorg(const char *name, int ci){strncpy_s(fullname, name, len);CI = ci;}plorg::~plorg(){}void plorg::p_fix(int ci){CI = ci;}void plorg::show()const{cout << fullname << ", " << CI << endl; }//main.cpp#include "plorg.h"int main(){plorg pl;pl.show();pl.p_fix(32);pl.show();plorg pll("Plorgb", 27);pll.show();pll.p_fix(32);pll.show();cin.get();return 0;}8、//list.h#ifndef LIST_H_#define LIST_H_#include <iostream>#include <string>#include <stdio.h>using namespace std;typedef unsigned long Item;class List{private:enum { MAX = 10 };Item items[MAX];int head;int rear;public:List();bool isempty()const;bool isfull()const;bool add(const Item &item);bool cut(Item &item);void show()const;void visit(void(*pf)(Item &)); };#endif//list.cpp#include "list.h"List::List(){head = 0;rear = 0;}bool List::isempty()const{return rear == head;}bool List::isfull()const{return rear - head == MAX; }bool List::add(const Item &item) {if (rear < MAX){items[rear++] = item;return true;}elsereturn false;}bool List::cut(Item &item){if (rear < MAX){item = items[--rear];return true;}elsereturn false;}void List::show()const{for (int i = head; i < rear; i++)cout << items[i] << ", ";cout << endl;}void List::visit(void(*pf)(Item &)){for (int i = 0; i < rear; i++)(*pf)(items[i]);}//main.cpp#include "list.h"void show_s(Item & item);int main(){List st;char ch;unsigned long po;unsigned long *p = &po;cout << "Please enter A to add a purchase order,\n"<< "P to process a PO, or Q to quit.\n";while (cin >> ch && toupper(ch) != 'Q'){while (cin.get() != '\n')continue;if (!isalpha(ch)){cout << '\a';continue;}switch (ch){case 'A':case 'a':cout << "Enter a PO number to add: ";cin >> po;if (st.isfull())cout << "stack already full\n";elsest.add(po);break;case 'P':case 'p':if (st.isempty())cout << "stack already empty\n";else{st.cut(po);cout << "PO #" << po << "popped\n";}break;case 'V':case 'v':st.visit(show_s);}cout << "Please enter A to add a purchase order,\n"<< "P to process a PO, or Q to quit.\n";}st.show();cout << "Bye\n";cin.get();cin.get();return 0;}void show_s(Item &item){item += 100;cout << item << endl;}。

CPrimerPlus第6版中文版勘误表

CPrimerPlus第6版中文版勘误表

注意:下面的勘误中,红色字体为修改后的文字,提请各位读者注意。

第 6 页,” 1.6 语言标准”中的第 3 行,将 1987 年修改为 1978 年。

第 22 页,” 2. main ()函数”中的第 1 行, int main (void ) 后面的分号( ; )删除。

第 24 页,“5. 声明”的第 10 行,也就 是一个变量、函数或其他实体的名称。

第 27 页,图 2.3 中,下划线应该只包含括号中的内容;第 2 段的第 4 行,而不是存储 在 源代码 中的指令。

第 30页,“2.5.4 打印多个值”的第 4行,双引 号后面的第 1 个变量。

第 34页,“2.7.3 程序状态”第 2段的第 4 行,要尽量忠实 于代码来模拟。

第 35页,“2.10 本章小结”第 2段的第 1句,声明 语句为变量指定变量名, 并标识该变量中存 储的数据类型;本页倒数第 2 行,即 检查程序每执行一步后所有变量的值。

第37页,“2.12编程练习”中第1题,把你的名和姓打印在一行……把你的 名和姓分别打印在 两行……把你的 名和姓打印在一行……把示例的内容换成你的 名字。

第 40 页,第 1 行,用于把英 磅常衡盎司转换为… … 第44页,“3.4 C 语言基本数据类型”的第 1句,本节将 详细介绍C 语言的基本属性类型……第 46页,“5. 八进制和十六进制”的第 4句,十六进制数 3的二进制数 是 0011,十六进制数 5 的二进制数 是 0101;“6. 显示八进制和十六进制”的第 1 句,既可以使用 也可以 显示不同进制 的数;将“回忆一下……程序在执行完毕后不会立即关闭执行窗口”放到一个括号里。

第 47页,“2. 使用多种整数类型的原因”第 3句,过去的一台运行 Windows 3.x 的机器上。

第 53 页,图 3.5 下面的第 4 行“上面最后一个例子( printf ( “ ” a \\ is abackslash. ” \n ” ); )” 第 56页,正文的第 2行和第 4行应该分别为 printf ( “me32 = %““d”“\n ”, me32); printf ( “me32 = %d\n ” , me32);第 61 页,“无符号类型”的最后 1 句,相当于 unsigned int (即两者之间添加一个空格 )。

C++ primer plus第六版知识要点(上)

C++ primer plus第六版知识要点(上)

C++ primer plus要点1.P28 开平方函数#include<cmath> sqrt()。

2.P34 让程序访问std名称空间的方法主要有两大类:使用using编译指令,如using namespace std,using std::cout;不使用编译指令,直接使用std::cout等。

3.P40 sizeof运算符返回类型或变量的长度,单位是字节。

4.P40 #include<climits>文件包含了整型限制信息,如INT_MAX,SHRT_MAX,LONG_MAX,LLONG_MAX等。

P41更详细。

5.利用预处理器定义符号常量#define NUMBER 1 后面没有;。

6.cout<<oct 此后输出8进制数,cout<<dec 此后输出10进制数类似还有hex。

7.cout.put(ch) 作用于字符输出。

8.P66 可通过强制类型转换来显示ASCII码 cout<<int(ch);9.P73 数组的初始化规则10.P76 求C风格字符串长度 #include<cstring> strlen() 不包含结尾处的空字符。

11.利用回车键发送输入时,可以理解输入内容最后一个字符为换行符(空白的一种),不要忘掉最后这个换行符。

?12.P80 char c=cin.get()(该函数无参数)或者char c cin.get(c),可以读取控制台里输入的一个字符串。

重要掌握后一个。

13.P87 string str; str对象的长度自动设置为0。

getline(cin,str)用来获取一行的输入。

14.P100 C++创建指针风格 int* p; 注意空格的位置,强调了int*是指一种复合类型。

15.P101 指针变量所占空间可能为4个字节。

16.P102指针变量的值不能和整型变量的值相互自动转换,必须显式强制转换。

勘误表

勘误表

勘误表“参考文献”放在书的最后一页。

详细修改请看《校正本》的前言,目录及各页。

第一章1. 第10页,最后一行:122424B m C P ==应该改为:122B m C ==2. 第19页第2题:C={20世纪90年代出版的书} 改为:C={21世纪出版的书}3. 第238页第2题的答案应该改为:(1)“21世纪以前出版的英文版数学书”;(2)在“馆中所有数学书都是21世纪出版的英文书”的条件下,等式成立;(3)“21世纪以前出版的书都是英文版的”;(4)“馆中非数学书都是英文版的,并且所有的英文版的书都不是数学书”4. 第20页,第5题最后一行:“恰好为1,2,3,4的概率”应该改为“恰好为1,2,3,4,5的概率” ,并把最后一行紧接到上一行的后面。

5. 第238页第5题的答案(3)“15”应该改为“25!”6. 第20页,第14题:“求()()P B A B P B ⋅ ”应该改为:“求()P B A B ”7. 第238页第15题(1)的答案“22222rrnn rnC C ”应该改为:“22222rrnrnC C ”8. 第239页第36题的答案“0.632”错误,应该改为()1111111234!!!!n n --+-++-9. 第22页,第38题第二行:“输出AAAA ,BBBB ,CCCC 的概率分别为”应该改为:“输入AAAA ,BBBB ,CCCC 的概率分别为”10. 第239页第39题的答案(2)()()222094006..N n C β-=应该改为:()()222094006..n n C β-=11.第239页26题的答案,应该是0.36,而非0.35第二章1、P26定义2.2.3上面一行P (X=k )改为P {X=k }2、 改为3、 P29例6(1) -12=ee λλ-⎛⎫ ⎪⎝⎭()1(1)n p kn k pkqkq+-+-=+()()p q kqkp n kqpk n -=-++=-+=111)1(改为2=ee 1-λλ-⎛⎫ ⎪⎝⎭(2) 中删去D={有两个乙类细菌};另外P(C) -12=ee λλ-⎛⎫ ⎪⎝⎭改为P(C)2=e e 1-λλ-⎛⎫ ⎪⎝⎭()()()()()()()()()()222P A P D A P C D P D P A D P D C P C P C P C P C ====2211221e2!2=ee 8e λλλλλλ----⎛⎫⎪⎝⎭=⎛⎫⎛⎫ ⎪ ⎪⎝⎭⎝⎭改为()()()()222P A P C A P A C P C =222221e2!2=ee 18e 1λλλλλλ--⎛⎫⎪⎝⎭=⎛⎫⎛⎫-- ⎪ ⎪⎝⎭⎝⎭4、 P30定义2.2.5 ……..试验次数,称X 服从参数p 的几何分布。

C Primer Plus第6版编程练习答案(已下载)

C Primer Plus第6版编程练习答案(已下载)

C Primer Plus Sixth Edition Programming ExerciseSelected Answers Chapter 2 Programming ExercisesPE 2-­­1/* Programming Exercise 2-1 */#include <stdio.h> intmain(void){ printf("Gustav Mahler\n");printf("Gustav\nMahler\n");printf("Gustav ");printf("Mahler\n"); return0;}PE 2-­­3/* Programming Exercise 2-3 */#include <stdio.h> intmain(void){ int ageyears; /* age in years*/ int agedays; /* age in days*//* large ages may require the long type */ageyears = 101; agedays = 365 * ageyears;printf("An age of %d years is %d days.\n", ageyears, agedays);return 0;}PE 2-­­4/* Programming Exercise 2-4 */#include <stdio.h>void jolly(void);void deny(void); intmain(void){ jolly();jolly();jolly();deny();return 0; }void jolly(void){printf("For he's a jolly good fellow!\n");}void deny(void){printf("Which nobody can deny!\n");}PE 2-­­6/* Programming Exercise 2-6 */#include <stdio.h> intmain(void){ int toes;toes = 10;printf("toes = %d\n", toes);— printf("Twice toes = %d\n", 2 * toes);printf("toes squared = %d\n", toes * toes); return0;}/* or create two more variables, set them to 2 * toes and toes * toes */PE 2-­­8/* Programming Exercise 2-8 */#include <stdio.h>void one_three(void);void two(void); intmain(void){printf("starting now:\n");one_three();printf("done!\n"); return0;}void one_three(void){printf("one\n");two();printf("three\n");}void two(void){printf("two\n");}Chapter 3 Programming ExercisesPE 3-­­2/* Programming Exercise 3-2 */#include <stdio.h> intmain(void){int ascii;printf("Enter an ASCII code: ");scanf("%d", &ascii);printf("%d is the ASCII code for %c.\n", ascii, ascii);return 0;}PE 3-­­4/* Programming Exercise 3-4 */#include <stdio.h> intmain(void){ floatnum;printf("Enter a floating-point value: ");scanf("%f", &num);printf("fixed-point notation: %f\n", num);printf("exponential notation: %e\n", num);printf("p notation: %a\n", num); return 0;}—PE 3-­­6/* Programming Exercise 3-6 */#include <stdio.h> intmain(void){float mass_mol = 3.0e-23; /* mass of water molecule in grams */float mass_qt = 950; /* mass of quart of water in grams */float quarts; float molecules;printf("Enter the number of quarts of water: ");scanf("%f", &quarts);molecules = quarts * mass_qt / mass_mol;printf("%f quarts of water contain %e molecules.\n", quarts, molecules); return 0;}Chapter 4 Programming ExercisesPE 4-­­1/* Programming Exercise 4-1 */#include <stdio.h> intmain(void){ charfname[40]; charlname[40];printf("Enter your first name: ");scanf("%s", fname); printf("Enteryour last name: "); scanf("%s",lname); printf("%s, %s\n", lname,fname); return 0;}PE 4-­­4/* Programming Exercise 4-4 */#include <stdio.h> intmain(void){ float height;char name[40];printf("Enter your height in inches: ");scanf("%f", &height); printf("Enter yourname: "); scanf("%s", name);printf("%s, you are %.3f feet tall\n", name, height / 12.0);return 0;}PE 4-­­7/* Programming Exercise 4-7 */#include <stdio.h>#include <float.h> intmain(void)—{ float ot_f = 1.0 / 3.0;double ot_d = 1.0 / 3.0;printf(" float values: ");printf("%.4f %.12f %.16f\n", ot_f, ot_f, ot_f);printf("double values: ");printf("%.4f %.12f %.16f\n", ot_d, ot_d, ot_d);printf("FLT_DIG: %d\n", FLT_DIG);printf("DBL_DIG: %d\n", DBL_DIG); return 0;}Chapter 5 Programming ExercisesPE 5-­­1/* Programming Exercise 5-1 */#include <stdio.h> intmain(void){ const int minperhour =60; int minutes, hours,mins;printf("Enter the number of minutes to convert: ");scanf("%d", &minutes); while (minutes > 0 ){ hours = minutes /minperhour; mins = minutes %minperhour;printf("%d minutes = %d hours, %d minutes\n", minutes, hours, mins); printf("Enter next minutes value (0 to quit): "); scanf("%d",&minutes);}printf("Bye\n");return 0;}PE 5-­­3/* Programming Exercise 5-3 */#include <stdio.h> intmain(void){ const int daysperweek =7; int days, weeks,day_rem;printf("Enter the number of days: ");scanf("%d", &days); while (days > 0){ weeks = days /daysperweek; day_rem = days %daysperweek;printf("%d days are %d weeks and %d days.\n",days, weeks, day_rem);printf("Enter the number of days (0 or less to end): ");scanf("%d", &days);}printf("Done!\n");return 0;—}PE 5-­­5/* Programming Exercise 5-5 */ #include<stdio.h>int main(void) /* finds sum of first n integers */{int count, sum;int n;printf("Enter the upper limit: ");scanf("%d", &n); count = 0;sum = 0; while(count++ < n) sum = sum + count;printf("sum = %d\n", sum); return0;}PE 5-­­7/* Programming Exercise 5-7 */#include <stdio.h> voidshowCube(double x);int main(void) /* finds cube of entered number */{ doubleval;printf("Enter a floating-point value: ");scanf("%lf", &val); showCube(val);return 0; }void showCube(double x){printf("The cube of %e is %e.\n", x, x*x*x );}Chapter 6 Programming ExercisesPE 6-­­1/* pe6-1.c *//* this implementation assumes the character codes *//* are sequential, as they are in ASCII. */#include <stdio.h> #define SIZE26 int main( void ) { charlcase[SIZE]; int i;for (i = 0; i < SIZE; i++)lcase[i] = 'a' + i; for (i= 0; i < SIZE; i++)printf("%c", lcase[i]);printf("\n");return 0;}PE 6-­­3/* pe6-3.c *//* this implementation assumes the character codes *//* are sequential, as they are in ASCII. */—#include <stdio.h> intmain( void ){ char let ='F'; char start;char end;for (end = let; end >= 'A'; end--){for (start = let; start >= end; start--)printf("%c", start); printf("\n");}return 0;}PE 6-­­6/* pe6-6.c */ #include<stdio.h> intmain( void ){ int lower, upper,index; int square, cube;printf("Enter starting integer: ");scanf("%d", &lower); printf("Enterending integer: "); scanf("%d",&upper);printf("%5s %10s %15s\n", "num", "square","cube"); for (index = lower; index <= upper;index++){ square = index *index; cube = index *square;printf("%5d %10d %15d\n", index, square, cube);}return 0;}PE 6-­­8/* pe6-8.c */ #include<stdio.h> intmain( void ){ double n,m; doubleres;printf("Enter a pair of numbers: ");while (scanf("%lf %lf", &n, &m) == 2){res = (n - m) / (n * m);printf("(%.3g - %.3g)/(%.3g*%.3g) = %.5g\n", n, m, n, m, res);printf("Enter next pair (non-numeric to quit): ");}return 0;}PE 6-­­11/* pe6-11.c */—#include <stdio.h>#define SIZE 8 intmain( void ){ intvals[SIZE]; inti;printf("Please enter %d integers.\n", SIZE);for (i = 0; i < SIZE; i++) scanf("%d",&vals[i]);printf("Here, in reverse order, are the values you entered:\n");for (i = SIZE - 1; i >= 0; i--) printf("%d ", vals[i]);printf("\n"); return 0;}PE 6-­­13/* pe6-13.c *//* This version starts with the 0 power */#include <stdio.h>#define SIZE 8 intmain( void ){int twopows[SIZE];int i;int value = 1; /* 2 to the 0 */for (i = 0; i < SIZE; i++){ twopows[i] =value; value *= 2;}i = 0;do {printf("%d ", twopows[i]);i++; } while (i < SIZE);printf("\n");return 0;}PE 6-­­14/* pe-14.c *//* Programming Exercise 6-14 */#include <stdio.h>#define SIZE 8 intmain(void){ double arr[SIZE];double arr_cumul[SIZE];int i;printf("Enter %d numbers:\n",SIZE);for (i = 0; i < SIZE; i++){printf("value #%d: ", i + 1);scanf("%lf", &arr[i]); /* orscanf("%lf", arr + i); */}arr_cumul[0] = arr[0]; /* set first element */for (i = 1; i < SIZE; i++)— arr_cumul[i] = arr_cumul[i-1] + arr[i];for (i = 0; i < SIZE; i++)printf("%8g ", arr[i]);printf("\n"); for (i = 0; i <SIZE; i++) printf("%8g ",arr_cumul[i]); printf("\n");return 0;}PE 6-­­16/* pe6-16.c */#include <stdio.h>#define RATE_SIMP 0.10#define RATE_COMP 0.05#define INIT_AMT 100.0 intmain( void ){double daphne = INIT_AMT;double deidre = INIT_AMT;int years = 0;while (deidre <= daphne){ daphne += RATE_SIMP *INIT_AMT; deidre += RATE_COMP *deidre;++years; }printf("Investment values after %d years:\n", years);printf("Daphne: $%.2f\n", daphne); printf("Deidre:$%.2f\n", deidre); return 0;}Chapter 7 Programming ExercisesPE 7-­­1/* Programming Exercise 7-1 */#include <stdio.h> intmain(void){ char ch;int sp_ct = 0;int nl_ct = 0;int other = 0;while ((ch =getchar()) != '#'){if (ch == ' ')sp_ct++; else if (ch== '\n') nl_ct++;else other++;}printf("spaces: %d, newlines: %d, others: %d\n", sp_ct, nl_ct, other);return 0;}—PE 7-­­3/* Programming Exercise 7-3 */#include <stdio.h> intmain(void){ int n; doublesumeven = 0.0; intct_even = 0; doublesumodd = 0.0; intct_odd = 0;while (scanf("%d", &n) == 1 && n != 0){if (n % 2 == 0){sumeven += n;++ct_even;}else // n % 2 is either 1 or -1{sumodd += n;++ct_odd;}}printf("Number of evens: %d", ct_even);if (ct_even > 0)printf(" average: %g", sumeven / ct_even);putchar('\n');printf("Number of odds: %d", ct_odd);if (ct_odd > 0)printf(" average: %g", sumodd / ct_odd);putchar('\n'); printf("\ndone\n");return 0;}PE 7-­­5/* Programming Exercise 7-5 */#include <stdio.h> intmain(void){ char ch;int ct1 = 0;int ct2 = 0;while ((ch =getchar()) != '#'){switch(ch){case '.' : putchar('!');++ct1; break;case '!' : putchar('!');putchar('!');++ct2; break;default : putchar(ch);}}printf("%d replacement(s) of . with !\n", ct1);printf("%d replacement(s) of ! with !!\n", ct2);—return 0;}PE 7-­­7// Programming Exercise 7-7#include <stdio.h>#define BASEPAY 10 // $10 per hour#define BASEHRS 40 // hours at basepay#define OVERTIME 1.5 // 1.5 time#define AMT1 300 // 1st rate tier#define AMT2 150 // 2st rate tier#define RATE1 0.15 // rate for 1st tier#define RATE2 0.20 // rate for 2nd tier#define RATE3 0.25 // rate for 3rd tier intmain(void){double hours;double gross;double net; doubletaxes;printf("Enter the number of hours worked this week: ");scanf("%lf", &hours); if (hours <= BASEHRS)gross = hours * BASEPAY; elsegross = BASEHRS * BASEPAY + (hours - BASEHRS) * BASEPAY * OVERTIME;if (gross <= AMT1) taxes = gross * RATE1; else if (gross <=AMT1 + AMT2)taxes = AMT1 * RATE1 + (gross - AMT1) * RATE2;elsetaxes = AMT1 * RATE1 + AMT2 * RATE2 + (gross - AMT1 - AMT2) * RATE3;net = gross - taxes;printf("gross: $%.2f; taxes: $%.2f; net: $%.2f\n", gross, taxes, net);return 0;}PE 7-­­9/* Programming Exercise 7-9 */#include <stdio.h>#include <stdbool.h> intmain(void){int limit;int num; intdiv;bool numIsPrime; // use int if stdbool.h not availableprintf("Enter a positive integer: ");while (scanf("%d", &limit) == 1 && limit > 0){if (limit > 1)printf("Here are the prime numbers up through %d\n", limit);elseprintf("No primes.\n");for (num = 2; num <= limit; num++){—for (div = 2, numIsPrime = true; (div * div) <= num; div++) if (num % div == 0) numIsPrime = false;if (numIsPrime)printf("%d is prime.\n", num);}printf("Enter a positive integer (q to quit): ");}printf("Done!\n");return 0;}PE 7-­­11/* pe7-11.c *//* Programming Exercise 7-11 */#include <stdio.h>#include <ctype.h> intmain(void){const double price_artichokes = 2.05;const double price_beets = 1.15;const double price_carrots = 1.09;const double DISCOUNT_RATE = 0.05;const double under5 = 6.50; constdouble under20 = 14.00; const doublebase20 = 14.00; const double extralb= 0.50;charch;double lb_artichokes = 0;double lb_beets = 0;double lb_carrots = 0;double lb_temp; doublelb_total;doublecost_artichokes; doublecost_beets; doublecost_carrots; doublecost_total; doublefinal_total; doublediscount; doubleshipping;printf("Enter a to buy artichokes, b for beets, ");printf("c for carrots, q to quit: "); while ((ch =getchar()) != 'q' && ch != 'Q'){ if (ch == '\n')continue; while(getchar() != '\n')continue; ch =tolower(ch); switch (ch){case 'a' : printf("Enter pounds of artichokes: ");scanf("%lf", &lb_temp); lb_artichokes+= lb_temp; break;case 'b' : printf("Enter pounds of beets: ");scanf("%lf", &lb_temp); lb_beets+= lb_temp; break;case 'c' : printf("Enter pounds ofcarrots: "); scanf("%lf", &lb_temp);lb_carrots += lb_temp; break;default : printf("%c is not a valid choice.\n", ch);}— printf("Enter a to buy artichokes, b for beets, ");printf("c for carrots, q to quit: ");}cost_artichokes = price_artichokes * lb_artichokes;cost_beets = price_beets * lb_beets; cost_carrots =price_carrots * lb_carrots; cost_total = cost_artichokes+ cost_beets + cost_carrots; lb_total = lb_artichokes +lb_beets + lb_carrots; if (lb_total <= 0) shipping= 0.0; else if (lb_total < 5.0) shipping = under5;else if (lb_total < 20) shipping = under20; elseshipping = base20 + extralb * lb_total;if (cost_total > 100.0)discount = DISCOUNT_RATE * cost_total;else discount = 0.0;final_total = cost_total + shipping - discount;printf("Your order:\n");printf("%.2f lbs of artichokes at $%.2f per pound:$ %.2f\n",lb_artichokes, price_artichokes, cost_artichokes);printf("%.2f lbs of beets at $%.2f per pound: $%.2f\n",lb_beets, price_beets, cost_beets); printf("%.2f lbs ofcarrots at $%.2f per pound: $%.2f\n", lb_carrots,price_carrots, cost_carrots); printf("Total cost ofvegetables: $%.2f\n", cost_total); if (cost_total > 100)printf("Volume discount: $%.2f\n", discount);printf("Shipping: $%.2f\n", shipping);printf("Total charges: $%.2f\n", final_total);return 0; }Chapter 8 Programming ExercisesPE 8-­­1/* Programming Exercise 8-1 */#include <stdio.h>int main(void) { int ch;int ct = 0; while ((ch =getchar()) != EOF) ct++;printf("%d characters read\n", ct);return 0;}PE 8-­­3/* Programming Exercise 8-3 *//* Using ctype.h eliminates need to assume consecutive coding */#include <stdio.h>#include <ctype.h> intmain(void) { int ch;unsigned long uct = 0;unsigned long lct = 0;unsigned long oct = 0;while ((ch = getchar()) != EOF)if (isupper(ch)) uct++;else if (islower(ch))lct++; elseoct++;—printf("%lu uppercase characters read\n", uct);printf("%lu lowercase characters read\n", lct); printf("%luother characters read\n", oct);return 0;}/* or you could use if(ch >= 'A' && ch <= 'Z')uct++;else if (ch >= 'a' && ch <= 'z')lct++; else oct++;*/PE 8-­­5/* Programming Exercise 8-5 *//* binaryguess.c -- an improved number-guesser *//* but relies upon truthful, correct responses */#include <stdio.h> #include<ctype.h> int main(void){ int high = 100; int low =1; int guess = (high + low) /2; char response;printf("Pick an integer from 1 to 100. I will try to guess ");printf("it.\nRespond with a y if my guess is right, with"); printf("\nah if it is high, and with an l if it is low.\n"); printf("Uh...is yournumber %d?\n", guess);while ((response = getchar()) != 'y') /* get response */{if (response == '\n')continue;if (response != 'h' && response != 'l'){printf("I don't understand that response. Please enter h for\n"); printf("high, l for low, or y for correct.\n"); continue;}if (response == 'h')high = guess - 1; else if(response == 'l') low= guess + 1; guess =(high + low) / 2;printf("Well, then, is it %d?\n", guess);}printf("I knew I could do it!\n");return 0;}PE 8-­­7/* Programming Exercise 8-7 */#include <stdio.h>#include <ctype.h>#include <stdio.h>#define BASEPAY1 8.75 // $8.75 per hour#define BASEPAY2 9.33 // $9.33 per hour#define BASEPAY3 10.00 // $10.00 per hour#define BASEPAY4 11.20 // $11.20 per hour#define BASEHRS 40 // hours at basepay#define OVERTIME 1.5 // 1.5 time—#define AMT1 300 // 1st rate tier#define AMT2 150 // 2st rate tier#define RATE1 0.15 // rate for 1st tier#define RATE2 0.20 // rate for 2nd tier#define RATE3 0.25 // rate for 3rd tierint getfirst(void); void menu(void); intmain(void){ double hours;double gross;double net;double taxes;double pay;char response;menu();while ((response = getfirst()) != 'q'){if (response == '\n') /* skip over newlines */continue;response = tolower(response); /* accept A as a, etc. */switch (response){case 'a': pay = BASEPAY1; break;case 'b': pay = BASEPAY2; break; case'c': pay = BASEPAY3; break; case 'd':pay = BASEPAY4; break;default : printf("Please enter a, b, c, d, or q.\n"); menu();continue; // go to beginning of loop}printf("Enter the number of hours worked this week: ");scanf("%lf", &hours); if (hours <= BASEHRS)gross = hours * pay; elsegross = BASEHRS * pay + (hours - BASEHRS) * pay * OVERTIME;if (gross <= AMT1) taxes = gross * RATE1; else if(gross <= AMT1 + AMT2)taxes = AMT1 * RATE1 + (gross - AMT1) * RATE2;elsetaxes = AMT1 * RATE1 + AMT2 * RATE2 + (gross - AMT1 - AMT2) * RATE3;net = gross - taxes;printf("gross: $%.2f; taxes: $%.2f; net: $%.2f\n", gross, taxes, net); menu(); }printf("Done.\n");return 0;}void menu(void){printf("********************************************************""*********\n");printf("Enter the letter corresponding to the desired pay rate"" or action:\n");printf("a) $%4.2f/hr b) $%4.2f/hr\n", BASEPAY1,BASEPAY2);printf("c) $%5.2f/hr d) $%5.2f/hr\n", BASEPAY3,BASEPAY4); printf("q) quit\n");printf("********************************************************""*********\n");}int getfirst(void)—{ intch;ch = getchar();while (isspace(ch))ch = getchar(); while(getchar() != '\n')continue; return ch;}Chapter 9 Programming ExercisesPE 9-­­1/* Programming Exercise 9-1 */#include <stdio.h>double min(double, double); intmain(void){double x, y; printf("Enter twonumbers (q to quit): "); while(scanf("%lf %lf", &x, &y) == 2){ printf("The smaller number is %f.\n",min(x,y)); printf("Next two values (q to quit):");}printf("Bye!\n");return 0;}double min(double a, double b){return a < b ? a : b;}/* alternative implementation doublemin(double a, double b){ if (a < b)return a;elsereturn b;}*/PE 9-­­3/* Programming Exercise 9-3 */#include <stdio.h>void chLineRow(char ch, int c, int r); intmain(void){ char ch; int col, row;printf("Enter a character (# to quit): ");while ( (ch = getchar()) != '#')— { if (ch =='\n')continue;printf("Enter number of columns and number of rows: ");if (scanf("%d %d", &col, &row) != 2) break;chLineRow(ch, col, row);printf("\nEnter next character (# to quit): ");}printf("Bye!\n");return 0;}// start rows and cols at 0 voidchLineRow(char ch, int c, int r){int col, row;for (row = 0; row < r ; row++){for (col = 0; col < c; col++)putchar(ch); putchar('\n');}return;}PE 9-­­5/* Programming Exercise 9-5 */#include <stdio.h>void larger_of(double *p1, double *p2); intmain(void){double x, y; printf("Enter twonumbers (q to quit): "); while(scanf("%lf %lf", &x, &y) == 2){larger_of(&x, &y);printf("The modified values are %f and %f.\n", x, y);printf("Next two values (q to quit): ");}printf("Bye!\n");return 0;}void larger_of(double *p1, double *p2){ if (*p1 >*p2) *p2 =*p1; else*p1 = *p2;}// alternatively:/*void larger_of(double *p1, double *p2){*p1= *p2 = *p1 > *p2 ? *p1 : *p2;—}*/PE 9-­­8/* Programming Exercise 9-8 */ #include<stdio.h>double power(double a, int b); /* ANSI prototype */ intmain(void) { double x, xpow; int n; printf("Enter anumber and the integer power"); printf(" to which\nthenumber will be raised. Enter q"); printf(" to quit.\n");while (scanf("%lf%d", &x, &n) == 2){ xpow = power(x,n); /* function call*/ printf("%.3g to the power %d is %.5g\n", x, n,xpow); printf("Enter next pair of numbers or q toquit.\n");} printf("Hope you enjoyed this power trip --bye!\n"); return 0;} double power(double a, int b) /* function definition*/{ double pow =1; int i;if (b == 0){ if (a ==0)printf("0 to the 0 undefined; using 1 as the value\n");pow = 1.0; } else if (a == 0) pow = 0.0; else if (b >0) for(i = 1; i <= b; i++) pow *= a; else /* b< 0 */ pow = 1.0 / power(a, - b);return pow; /* return the value of pow */}PE 9-­­10/* Programming Exercise 9-10 */ #include<stdio.h> void to_base_n(int x, int base);int main(void) { int number; int b;int count; printf("Enter an integer (qto quit):\n"); while (scanf("%d", &number)== 1){ printf("Enter number base (2-10):"); while ((count = scanf("%d",&b))== 1&& (b < 2 || b > 10)){printf("base should be in the range 2-10: ");} if(count != 1)break;printf("Base %d equivalent: ", b);to_base_n(number, b); putchar('\n');printf("Enter an integer (q to quit):\n");}printf("Done.\n");return 0;}void to_base_n(int x, int base) /* recursive function */{ int r; r = x % base;if (x >= base) to_base_n(x—/ base, base); putchar('0' +r); return;}Chapter 10 Programming ExercisesPE 10-­­1/* Programming Exercise 10-1 */#include <stdio.h>#define MONTHS 12 // number of months in a year#define YRS 5 // number of years of data intmain(void){// initializing rainfall data for 2010 - 2014const float rain[YRS][MONTHS] = {{4.3,4.3,4.3,3.0,2.0,1.2,0.2,0.2,0.4,2.4,3.5,6.6},{8.5,8.2,1.2,1.6,2.4,0.0,5.2,0.9,0.3,0.9,1.4,7.3},{9.1,8.5,6.7,4.3,2.1,0.8,0.2,0.2,1.1,2.3,6.1,8.4},{7.2,9.9,8.4,3.3,1.2,0.8,0.4,0.0,0.6,1.7,4.3,6.2},{7.6,5.6,3.8,2.8,3.8,0.2,0.0,0.0,0.0,1.3,2.6,5.2}}; int year,month; float subtot,total;printf(" YEAR RAINFALL (inches)\n");for (year = 0, total = 0; year < YRS; year++){ /* for each year, sum rainfall for each month */for (month = 0, subtot = 0; month < MONTHS; month++)subtot += *(*(rain + year) + month); printf("%5d %15.1f\n",2010 + year, subtot);total += subtot; /* total for all years */}printf("\nThe yearly average is %.1f inches.\n\n", total/YRS);printf("MONTHLY AVERAGES:\n\n");printf(" Jan Feb Mar Apr May Jun Jul Aug Sep Oct ");printf(" Nov Dec\n");for (month = 0; month < MONTHS; month++){ /* for each month, sum rainfall over years */for (year = 0, subtot =0; year < YRS; year++) subtot+= *(*(rain + year) + month); printf("%4.1f ",subtot/YRS);}printf("\n");return 0;}PE 10-­­3/* Programming Exercise 10-3 */#include <stdio.h>#define LEN 10int max_arr(const int ar[], int n);void show_arr(const int ar[], int n);int main(void){— int orig[LEN] = {1,2,3,4,12,6,7,8,9,10};int max;show_arr(orig, LEN); max =max_arr(orig, LEN); printf("%d =largest value\n", max);return 0;}int max_arr(const int ar[], int n){ int i; intmax = ar[0];/* don't use 0 as initial max value -- fails if all array values are neg */for (i = 1; i < n; i++)if (max < ar[i])max = ar[i]; return max;}void show_arr(const int ar[], int n){ int i; for (i= 0; i < n; i++)printf("%d ", ar[i]);putchar('\n');}PE 10-­­5/* Programming Exercise 10-5 */#include <stdio.h>#define LEN 10double max_diff(const double ar[], int n); voidshow_arr(const double ar[], int n);int main(void){double orig[LEN] = {1.1,2,3,4,12,61.3,7,8,9,10};double max;show_arr(orig, LEN);max = max_diff(orig, LEN);printf("%g = maximum difference\n", max);return 0;}double max_diff(const double ar[], int n){ int i; doublemax = ar[0]; doublemin = ar[0];for (i = 1; i < n; i++){if (max < ar[i])max = ar[i]; else if(min > ar[i])min = ar[i];}return max - min;}void show_arr(const double ar[], int n)。

C++peimer勘误

C++peimer勘误

《C++ Primer 第四版》英文版一流,但中文版的翻译质量只能说一般,如同书评区某位兄弟说的:感觉是译者懂的一部分地方翻译得还可以,不懂的许多地方就硬翻或不求甚解。

结果导致有些译文严重不通,甚至无法理解。

建议对照英文版一起阅读,或者对照以下个人作出的勘误。

以下为本人读书过程中做的笔记和个人勘误(针对06年6月第2次印刷的版本),更多笔记和勘误在个人博客,喜欢C++编程的朋友欢迎到:/hzm共同进步。

---------------------------------《C++ Primer第四版》勘误:P13(第13页)“不是所有编译器都有这一要求”后半句应翻译为“都满足这一标准”。

影响阅读程度:严重说明:“编译器”如何能“要求”C++标准?原英文版中的“enforce”应翻译为“满足”而不是“有”,动宾关系才不会搞反。

P52 “仅允许const引用绑定到需要临时使用的值”应翻译为“仅允许const引用绑定到需要临时值中转来完成绑定过程的对象”影响程度:严重说明:译者对宾语的主体理解错误。

原英文版中的“临时使用的值”是用来修饰value(对象)的,不是最终的宾语。

因为对于程序员来说,编译器做的中转工作是透明的,const引用最终还是绑定到对象,虽然结果相同。

P43 “有多个初始化式时不能使用复制初始化”前半句应翻译为“有多个初始化参数时”。

影响程度:一般P45 “如果定义某个类的变量时没有提供初始化式….”这句和后一句应翻译为“如果定义某个类的变量时没有提供初始化参数,那么系统会调用该类的’缺省构造函数’。

”影响程度:一般P50 有三处的“const变量”翻译为“const常量”或“const对象”比较好,虽然原英文版有两处也是用const variable。

影响程度:轻微P65 “word(字)机器上的自然的整型计算单元”应翻译为“word (字)是在给定机器上进行整型计算的原始单元”影响程度:一般P79 “v4含有值初始化的元素”这句应翻译为“v4含有n个用缺省构造函数中的值初始化的元素”影响程度:严重P79 “动态地添加元素”这句应翻译为“当元素值已知时,最好是通过动态地向它添加元素,来让它增长。

《 C++ Primer Plus (第 6 版)中文版》 勘误表

《 C++ Primer Plus (第  6  版)中文版》 勘误表

================================================================= *** 《C++ Primer Plus (第6 版)中文版》勘误表***作者:yangyang.gnu联系:yangyang.gnu@时间:2013-9-24================================================================= P268错误: free_throws * pt;修正: free_throws * pt = new free_throws;P291错误:在这两个模板函数中,recycle<blot *>(blot *) 被认为是更具体的修正:在这两个模板函数中,recycle<blot>(blot *) 被认为是更具体的P337错误: staticconst LIMIT = 25;修正: staticconst unsigned LIMIT = 25;P386错误:t4 = t1 + t2 + t3 先转换为t4 = t1.operator+(t2 + t3) 再转换为t4 =t1.operator+(t2.operator+(t3))修正:t4 = t1 + t2 + t3 先转换为t4 = t1.operator+(t2) + t3 再转换为t4 =t1.operator+(t2).operator+(t3)P387错误:.*:成员指针运算符修正:->:成员指针运算符P428错误:String boston("Boston");修正:StringBadboston("Boston");P431错误:然后程序使用重载运算符>>列出了这些对象修正:然后程序使用重载运算符<<列出了这些对象P439错误:最简单的办法是使用标准的trcmp()函数修正:最简单的办法是使用标准的strcmp()函数P440错误:means.operator[][0] = 'r';修正:means.operator[](0) = 'r';P439错误:因为内置的>运算符返回的是一个布尔值修正:因为内置的<运算符返回的是一个布尔值P478错误:Cow(const Cow c& );修正:Cow(const Cow & c);P478错误:提供一个Stringlow()成员函数修正:提供一个stringlow()成员函数错误:提供String()成员函数修正:提供stringup()成员函数P505错误: 这意味着,即使基类不需要显式析构函数提供服务,也不应该依赖于默认构造函数修正: 这意味着,即使基类不需要显式析构函数提供服务,也不应该依赖于默认构造析构P508错误:半长轴修正:长半轴P510错误:void Move(intnx, ny) = 0修正:virtual void Move(intnx, ny) = 0P525错误:Star::Star double() {...}Star::Star const char * () {...}修正:Star::operator double() {...}Star::operator const char * () {...}P529错误:派生类的有元函数修正:派生类的友元函数P532错误:Cd(char * s1, char * s2, int n, double x);修正:Cd(const char * s1, const char * s2, int n, double x);P532错误:派生出一个Classic 类,并添加一组char 成员修正:派生出一个Classic 类,并添加一个char 数组成员P532错误:copy.Report()修正:copy.Report();P535错误:所有元素度被初始化为指定值的数组修正:所有元素都被初始化为指定值的数组P544错误:例如,在类声明中提出可以使用average()函数。

C++-primer-plus(第6版)中文版编程练习答案第13章

C++-primer-plus(第6版)中文版编程练习答案第13章

//cdplayer.h#ifndef CDPLAYER_H_#define CDPLAYER_H_#include <iostream>#include <string>using namespace std;class Cd{private:char performers[50];char label[20];int selections;double playtime;public:Cd(char *s1, char *s2, int n, double x);Cd(const Cd &d);Cd(){}virtual ~Cd();virtual void Report()const;Cd &operator=(const Cd &d);};class Classic :public Cd{private:char main_music[50];public:Classic(){}Classic(char *m, char *s1, char *s2, int n, double x);Classic(char *m, const Cd &c);~Classic();Classic &operator=(const Classic &c);virtual void Report()const;};#endif//cdplayer.cpp#include "cdplayer.h"Cd::Cd(char *s1, char *s2, int n, double x)strcpy_s(performers, strlen(s1) + 1, s1);strcpy_s(label, strlen(s2) + 1, s2);selections = n;playtime = x;}Cd::Cd(const Cd &d){strcpy_s(performers, 50, d.performers);strcpy_s(label, 20, bel);selections = d.selections;playtime = d.playtime;}Cd::~Cd(){}void Cd::Report()const{cout << "Performers: " << performers << endl;cout << "Label: " << label << endl;cout << "Selections: " << selections << endl;cout << "Playtime: " << playtime << endl;}Cd &Cd::operator=(const Cd &d){if (this == &d)return *this;strcpy_s(performers, 50, d.performers);strcpy_s(label, 20, bel);selections = d.selections;playtime = d.playtime;return *this;}Classic::Classic(char *m, char *s1, char *s2, int n, double x) :Cd(s1, s2, n, x) {strcpy_s(main_music, strlen(m) + 1, m);}Classic::Classic(char *m, const Cd &c) : Cd(c){strcpy_s(main_music, strlen(m) + 1, m);}Classic::~Classic(){}Classic &Classic::operator=(const Classic &c){if (this == &c)return *this;Cd::operator=(c);strcpy_s(main_music, 50, c.main_music);return *this;}void Classic::Report()const{Cd::Report();cout << "Main Music: " << main_music << endl;}//main.cpp#include "cdplayer.h"void Bravo(const Cd &disk);int main(){Cd c1("Beatles", "Capito", 14, 35.5);Classic c2 = Classic("Piano Sonata in B flat, Fantasia in C", "Alfred Brendel", "Philips", 2, 57.17);Cd *pcd = &c1;cout << "Using object directly:\n";c1.Report();c2.Report();cout << "Using type cd * pointer to objects:\n";pcd->Report();pcd = &c2;pcd->Report();cout << "Calling a function with a Cd reference argument:\n";Bravo(c1);Bravo(c2);cout << "Testing assignment: ";Classic copy;copy = c2;copy.Report();system("pause");return 0;}void Bravo(const Cd &disk){disk.Report();}2、//cdplayer.h#ifndef CDPLAYER_H_#define CDPLAYER_H_#include <iostream>#include <string>using namespace std;class Cd{private:char *performers;char *label;int selections;double playtime;public:Cd(char *s1, char *s2, int n, double x);Cd(const Cd &d);Cd(){}virtual ~Cd();virtual void Report()const;Cd &operator=(const Cd &d);};class Classic :public Cd{private:char *main_music;public:Classic(){}Classic(char *m, char *s1, char *s2, int n, double x);Classic(char *m, const Cd &c);~Classic();Classic &operator=(const Classic &c);virtual void Report()const;};#endif//cdplayer.cpp#include "cdplayer.h"Cd::Cd(char *s1, char *s2, int n, double x){performers = new char[strlen(s1) + 1];label = new char[strlen(s2) + 1];strcpy_s(performers, strlen(s1) + 1, s1);strcpy_s(label, strlen(s2) + 1, s2);selections = n;playtime = x;}Cd::Cd(const Cd &d){performers = new char[strlen(d.performers) + 1];label = new char[strlen(bel) + 1];strcpy_s(performers, strlen(d.performers) + 1, d.performers);strcpy_s(label, strlen(bel) + 1, bel);selections = d.selections;playtime = d.playtime;}Cd::~Cd(){delete[]performers;delete[]label;}void Cd::Report()const{cout << "Performers: " << performers << endl;cout << "Label: " << label << endl;cout << "Selections: " << selections << endl;cout << "Playtime: " << playtime << endl;}Cd &Cd::operator=(const Cd &d){if (this == &d)return *this;delete[]performers;delete[]label;performers = new char[strlen(d.performers) + 1];label = new char[strlen(bel) + 1];strcpy_s(performers, strlen(d.performers) + 1, d.performers);strcpy_s(label, strlen(bel) + 1, bel);selections = d.selections;playtime = d.playtime;return *this;}Classic::Classic(char *m, char *s1, char *s2, int n, double x) :Cd(s1, s2, n, x) {main_music = new char[strlen(m) + 1];strcpy_s(main_music, strlen(m) + 1, m);}Classic::Classic(char *m, const Cd &c) : Cd(c){main_music = new char[strlen(m) + 1];strcpy_s(main_music, strlen(m) + 1, m);}Classic::~Classic(){delete[]main_music;}Classic &Classic::operator=(const Classic &c){if (this == &c)return *this;Cd::operator=(c);delete[]main_music;main_music = new char[strlen(c.main_music) + 1];strcpy_s(main_music, strlen(c.main_music) + 1, c.main_music);return *this;}void Classic::Report()const{Cd::Report();cout << "Main Music: " << main_music << endl;}//main.cpp#include "cdplayer.h"void Bravo(const Cd &disk);int main(){Cd c1("Beatles", "Capito", 14, 35.5);Classic c2 = Classic("Piano Sonata in B flat, Fantasia in C", "Alfred Brendel", "Philips", 2, 57.17);Cd *pcd = &c1;cout << "Using object directly:\n";c1.Report();c2.Report();cout << "Using type cd * pointer to objects:\n";pcd->Report();pcd = &c2;pcd->Report();cout << "Calling a function with a Cd reference argument:\n";Bravo(c1);Bravo(c2);cout << "Testing assignment: ";Classic copy;copy = c2;copy.Report();system("pause");return 0;}void Bravo(const Cd &disk){disk.Report();}3、//dma.h#ifndef DMA_H_#define DMA_H_#include <iostream>#include <string>using namespace std;class ABC{private:char *fullname;int level;public:ABC(const char *f = "null", int l = 0);ABC(const ABC &ab);ABC &operator=(const ABC &ab);virtual ~ABC();virtual void View() = 0;};class baseDMA :public ABC{private:char *label;int rating;public:baseDMA(const char *l = "null", int r = 0, const char *f = "null", int lv = 0);baseDMA(const baseDMA &rs);~baseDMA();baseDMA &operator=(const baseDMA &rs);virtual void View();};class lacksDMA :public ABC{private:enum{ COL_LEN = 40 };char color[COL_LEN];public:lacksDMA(const char *c = "blank", const char *f = "null", int lv = 0);lacksDMA(const char *c, const baseDMA &rs);virtual void View();};class hasDMA :public ABC{private:char *style;public:hasDMA(const char *s = "none", const char *f = "null", int lv = 0);hasDMA(const char *s, const ABC &rs);hasDMA(const hasDMA &hs);~hasDMA();hasDMA &operator=(const hasDMA &hs);virtual void View();};#endif//dma.cpp#include "dma.h"ABC::ABC(const char *f, int lv){fullname = new char[strlen(f) + 1];strcpy_s(fullname, strlen(f) + 1, f);level = lv;}ABC::ABC(const ABC &ab){fullname = new char[strlen(ab.fullname) + 1];strcpy_s(fullname, strlen(ab.fullname) + 1, ab.fullname);level = ab.level;}ABC::~ABC(){delete[]fullname;}ABC &ABC::operator=(const ABC &ab){if (this == &ab)return *this;delete[]fullname;fullname = new char[strlen(ab.fullname) + 1];strcpy_s(fullname, strlen(ab.fullname) + 1, ab.fullname);level = ab.level;return *this;void ABC::View(){cout << "Fullname: " << fullname << endl;cout << "Level: " << level << endl;}baseDMA::baseDMA(const char *l, int r, const char *f, int lv) :ABC(f, lv) {label = new char[strlen(l) + 1];strcpy_s(label, strlen(l) + 1, l);rating = r;}baseDMA::baseDMA(const baseDMA &rs) :ABC(rs){label = new char[strlen(bel) + 1];strcpy_s(label, strlen(bel) + 1, bel);rating = rs.rating;}baseDMA::~baseDMA(){delete[]label;}baseDMA &baseDMA::operator=(const baseDMA &rs){if (this == &rs)return *this;ABC::operator=(rs);delete[]label;label = new char[strlen(bel) + 1];strcpy_s(label, strlen(bel) + 1, bel);rating = rs.rating;return *this;}void baseDMA::View(){ABC::View();cout << "Label: " << label << endl;cout << "Rating: " << rating << endl;}lacksDMA::lacksDMA(const char *c, const char *f, int lv) :ABC(f, lv){strncpy_s(color, c, 39);color[39] = '\0';}lacksDMA::lacksDMA(const char *c, const baseDMA &rs) : ABC(rs) {strncpy_s(color, c, COL_LEN - 1);color[COL_LEN - 1] = '\0';}void lacksDMA::View(){ABC::View();cout << "Color: " << color << endl;}hasDMA::hasDMA(const char *s, const char *f, int lv) :ABC(f, lv) {style = new char[strlen(s) + 1];strcpy_s(style, strlen(s) + 1, s);}hasDMA::hasDMA(const char *s, const ABC &ab) :ABC(ab){style = new char[strlen(s) + 1];strcpy_s(style, strlen(s) + 1, s);}hasDMA::hasDMA(const hasDMA &hs) : ABC(hs){style = new char[strlen(hs.style) + 1];strcpy_s(style, strlen(hs.style) + 1, hs.style);}hasDMA::~hasDMA(){delete[]style;}hasDMA &hasDMA::operator=(const hasDMA &hs){if (this == &hs)return *this;ABC::operator=(hs);delete[]style;style = new char[strlen(hs.style) + 1];strcpy_s(style, strlen(hs.style) + 1, hs.style);return *this;}void hasDMA::View(){ABC::View();cout << "Style: " << style << endl;}//usedma.cpp#include "dma.h"int main(){baseDMA shirt("Portabelly", 8, "Jack", 1);lacksDMA balloon("red", "Blimpo", 4);hasDMA map("Mercator", "buffalo Keys", 5);cout << "Displaying baseDMA object:\n";shirt.View();cout << "Displaying lacksDMA object:\n";balloon.View();cout << "Displaying hasDMA object:\n";map.View();lacksDMA balloon2(balloon);cout << "Result of lacksDMA copy:\n";balloon2.View();hasDMA map2;map2 = map;cout << "Result of hasDMA assignment:\n";map2.View();system("pause");return 0;}4、//port.h#ifndef PORT_H_#define PORT_H_#include <iostream>#include <cstring>using namespace std;class Port{private:char *brand;char style[20];int bottles;public:Port(const char *br = "none", const char *st = "none", int b = 0);Port(const Port &p);virtual ~Port(){ delete[]brand; }Port &operator=(const Port &p);Port &operator+=(int b);Port &operator-=(int b);int BottleCount()const{ return bottles; }virtual void Show()const;friend ostream &operator<<(ostream &os, const Port &p);};class VintagePort :public Port{private:char *nickname;int year;public:VintagePort();VintagePort(const char *br, const char *st, int b, const char *nn, int y);VintagePort(const VintagePort &vp);~VintagePort(){ delete[]nickname; }VintagePort &operator=(const VintagePort &vp);void Show()const;friend ostream &operator<<(ostream &os, const VintagePort &vp);};#endif//port.cpp#include "port.h"Port::Port(const char *br, const char *st, int b){brand = new char[strlen(br) + 1];strcpy_s(brand, strlen(br) + 1, br);strcpy_s(style, strlen(st) + 1, st);bottles = b;}Port::Port(const Port &p){brand = new char[strlen(p.brand) + 1];strcpy_s(brand, strlen(p.brand) + 1, p.brand);strcpy_s(style, strlen(p.style) + 1, p.style);bottles = p.bottles;}Port &Port::operator=(const Port &p){if (this == &p)return *this;delete[]brand;brand = new char[strlen(p.brand) + 1];strcpy_s(brand, strlen(p.brand) + 1, p.brand);strcpy_s(style, strlen(p.style) + 1, p.style);bottles = p.bottles;return *this;}Port &Port::operator+=(int b){bottles += b;return *this;}Port &Port::operator-=(int b){bottles -= b;return *this;}void Port::Show()const{cout << "Brand: " << brand << endl;cout << "Kind: " << style << endl;cout << "Bottles: " << bottles << endl;}ostream &operator<<(ostream &os, const Port &p){os << p.brand << ", " << p.style << ", " << p.bottles;return os;}VintagePort::VintagePort(){nickname = new char[1];nickname[0] = '\0';year = 0;}VintagePort::VintagePort(const char *br, const char *st, int b, const char *nn, int y) :Port(br, st, b){nickname = new char[strlen(nn) + 1];strcpy_s(nickname, strlen(nn) + 1, nn);year = y;}VintagePort::VintagePort(const VintagePort &vp) :Port(vp){nickname = new char[strlen(vp.nickname) + 1];strcpy_s(nickname, strlen(vp.nickname) + 1, vp.nickname);year = vp.year;}VintagePort &VintagePort::operator=(const VintagePort &vp){if (this == &vp)return *this;delete[]nickname;Port::operator=(vp);nickname = new char[strlen(vp.nickname) + 1];strcpy_s(nickname, strlen(vp.nickname) + 1, vp.nickname);year = vp.year;return *this;}void VintagePort::Show()const{Port::Show();cout << "Nickname: " << nickname << endl;cout << "Year: " << year << endl;}ostream &operator<<(ostream &os, const VintagePort &vp){os << (const Port &)vp;os << ", " << vp.nickname << ", " << vp.year;return os;}//main.cpp#include "port.h"int main(){Port wine1("Gallo", "tawny", 20);VintagePort wine2("Romane Conti", "vintage", 10, "The Noble", 1876);VintagePort wine3("Merlot", "ruby", 30, "Old Velvet", 1888);cout << "Displaying Port object:\n";wine1.Show();cout << wine1 << endl;cout << "Displaying VintagePort object:\n";wine2.Show();cout << wine2 << endl;cout << "Displaying VintagePort object:\n";wine3.Show();cout << wine3 << endl;cout << "Gallo add ten bottles:\n";wine1 += 10;cout << wine1 << endl;cout << "Romane Conti add ten bottles:\n";wine2 += 10;cout << wine2 << endl;cout << "Merlot minus ten bottles:\n";wine3 -= 10;cout << wine3 << endl;Port wine4(wine2);cout << "Result of Port copy:\n";cout << wine4 << endl;VintagePort wine5;wine5 = wine3;cout << "Result of VintagePort assignment:\n";cout << wine5 << endl;system("pause");return 0;}(注:可编辑下载,若有不当之处,请指正,谢谢!)。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C P r i m e r P l u s第6版中文版勘误表注意:下面的勘误中,红色字体为修改后的文字,提请各位读者注意。

1.第6页,” 1.6语言标准”中的第3行,将1987年修改为1978年。

2.第22页,” 2. main()函数”中的第1行,int main (void)后面的分号(;)删除。

3.第24页,“5. 声明”的第10行,也就是一个变量、函数或其他实体的名称。

4.第27页,图2.3中,下划线应该只包含括号中的内容;第2段的第4行,而不是存储在源代码中的指令。

5.第30页,“2.5.4 打印多个值”的第4行,双引号后面的第1个变量。

6.第34页,“2.7.3 程序状态”第2段的第4行,要尽量忠实于代码来模拟。

7.第35页,“2.10 本章小结”第2段的第1句,声明语句为变量指定变量名,并标识该变量中存储的数据类型;本页倒数第2行,即检查程序每执行一步后所有变量的值。

8.第37页,“2.12 编程练习”中第1题,把你的名和姓打印在一行……把你的名和姓分别打印在两行……把你的名和姓打印在一行……把示例的内容换成你的名字。

9.第40页,第1行,用于把英磅常衡盎司转换为……10.第44页,“3.4 C语言基本数据类型”的第1句,本节将详细介绍C语言的基本属性类型……11.第46页,“5. 八进制和十六进制”的第4句,十六进制数3的二进制数是0011,十六进制数5的二进制数是0101;“6.显示八进制和十六进制”的第1句,既可以使用也可以显示不同进制的数;将“回忆一下……程序在执行完毕后不会立即关闭执行窗口”放到一个括号里。

12.第47页,“2.使用多种整数类型的原因”第3句,过去的一台运行Windows 3.x的机器上。

13.第53页,图 3.5下面的第4行“上面最后一个例子(printf(“Gramps sez, \”a \\ is abackslash.\”\n”);)”14.第56页,正文的第2行和第4行应该分别为printf(“me32= %“ “d” “\n”, me32); printf(“me32= %d\n”, me32);15.第61页,“无符号类型”的最后1句,相当于unsigned int(即两者之间添加一个空格)。

16.第62页,程序清单3.8中的第1行,将//* typesize.c -- 打印类型大小*/中的第一个斜杠删除。

17.第63页,“3.6参数和陷阱”第2行,printf(“Hello,pal.”)(即Hello,和pal.之间没有空格)。

18.第64页,程序清单3.10中的第1行,使用转义序列。

19.第75页,倒数第8行,何时使用圆括号取决于运算对象是类型还是特定量。

20.第82页,第11行,……格式字符串包含了两个待打印项number和pies对应的……21.第83页,表4.4中的“L”修饰符的含义介绍中,应该是示例:”%L f”、“%10.4L e”22.第84页,表4.5中的第1行,即,从字段的左侧开始打印该项(即,应该只保留一个项);在“0”标记的含义中,添加一行:示例:"%010d"和"%08.3f"。

23.第86页,第1段的第2行,……字段宽度是容纳待打印数字所需的……;倒数第4段中,根据%x打印出1f,根据%X打印出1F24.第87页,“4.4.4转换说明的意义”第2段,……读者认为原始值被替换成转换后的值。

25.第89页,“参数传递”第2行,把变量n1、n2、n3和n4的值传递给程序(即,保留一个顿号)。

26.第93页,第5行的2121.45的字体应该与第4行的42的字体保持一致;表4.6上面的最后一行,对于double类型要使用1修饰符。

27.第94页,表中的第3行,把对应的数值存储为unsigned short int类型;把“j”转换说明的示例放到“z”转换说明中;在“j”转换说明的含义中添加:示例:”%jd”、”%ju”。

28.第95页,“3.scanf( )的返回值”上面一段的倒数第3行,如果在格式字符串中把空格放到%c的前面。

29.第98页,倒数第2段,strlen( )函数(声明在string.h头文件中)可用于……。

30.第100页,”4.8编程练习”中的第2题,将该题中的“名和姓”统一替换为“名字”;并执行以下操作;第3题,将a、b项中的“输入”替换为”The input is”,将“或”替换为“or”,将末尾的分号换成点(.)。

31.第105页,第8行,由于19.0不小于18.5,所以该条件为假。

32.第107页,程序清单5.3下面的第1行,首先把68赋给jane。

33.第111页,图5.3下面的第1行,如何让加法运算在除法运算之前执行。

34.第117页,程序清单5.11结束后的第4行,而pre_b是b递增之后的值。

35.第118页,倒数第2行,而不是(x*y)++。

36.第129页,程序清单5.15的第4行,//1小时的秒数。

37.第134页,“5.11编程练习”中的第4题,168.7 cm = 5 feet, 6.4 inches38.第143页,正文第2段,假设你想跳过输入到达第1个既不是空白字符也不是数字的位置39.第148页,倒数第3行,高优先级组:< <= > >=(即在<和<=之间有空格,在>和>=之间有空格)40.第153页,第7行的“15”与下一行的“28”左对齐。

41.第161页,“小结:do while语句”中的倒数第4行,在expression为假或0之前(注意要用斜体)42.第167页,程序清单6.20的名字应该是power.c程序(即删除一个w)43.第170页,“6.15复习题”第1题,后5行中使用的是前一行生成的quack的值。

44.第175页,第10题的第3句话,用户输入的上限整数等于或小于下限整数为止。

45.第178页,中间部分的文字中,if语句指示几岁安及,如果刚读取的值(t emperature)小于0。

46.第185页,正文第2段,特别要注意的是,如果kwh大于360;中间代码之后的第1句,也就是说,该程序由一个if else语句组成(即,if和else之间要有一个空格)47.第187页,正文倒数第2段,倒数第3行,2和72、3和48、4和36。

48.第196页,代码中第2行,达到单词的末尾。

49.第212页,复习题的第4题,下列各表达式的值是多少。

50.第215页,第2题的第2句话,每行打印8个“字符-ASCII码”组合;第7题的a项中,10.00美元/小时。

51.第222页,“8.4重定向和文件”的第2句话,输入设备(我们假设)是键盘;“8.4.1UNIX、Linux和DOS重定向”的上面一段,重定向的一个主要问题是它与操作系统有关;苹果OS X运行在UNIX上,故可用Terminal应用程序来使用UNIX命令行模式。

52.第224页,“3.组合重定向”中的第2、4、6行中,应该是分别是./echo_eof < mywords >savewords、./echo_eof > savewords < mywords、./echo_eof < mywords > mywords….;第13行应该是./echo_eof<words;第16、17、18、19行的多买中,均在最前面添加./53.第225页,“小结:如何重定向输入和输出”中的4行代码中,均在前面添加./54.第227页,正文中间,该程序还是会把f视为n(即这里将“被”删除)。

55.第245页,倒数第6行中,程序中starbar( )和main( )的定义形式相同。

56.第247页,“9.1.3 函数参数”中第2段最后1行,因此,可以调用show_n_char(‘ ‘, 12)(即两个单引号之间是一个空格)57.第260页,第19行,因此,n乘以n-1的阶乘就得到n的阶乘。

58.第268页,程序清单9.13上面的一行,在interchange( )中使用u和v。

59.第272页,倒数第7行,让interchange( )访问这两个变量。

60.第273页,“变量:名称、地址和值”中第3段第2行,使用变量名即可获得变量的数值。

61.第276页,“9.11编程练习”第6题,把最小值放入第一个变量;第10题,编写一个to_base_n()函数接受两个参数,且第2个参数在2~10范围内,然后以第2个参数……。

62.第285页,第11行,float rain[5][12];(即float和rain之间有一个空格);图10.1上面的一句话,则使用rain[1][2];顺便将括号以及括号中的文字删除。

63.第289页,图10.3上面一段的第2行,这意味着加1后的地址是下一个元素的地址(即,将“把”删除)64.第290页,第1行,dates + 2 == &date s[2]65.第295页,第3行,至于C语言,ar[i]和*(ar+i)这两个表达式都是等价的。

66.第305页,正文倒数第3段,第2行,指向一个内含3个int类型元素的数组;pa指向一个内含3个int类型元素的数组。

67.第307页,程序清单10.17上面的一段,这样的变量稍后能以同样的方式用作junk。

68.第316页,第6题,在a、b、c这3项的后面添加“的地址”69.第322页,上面第2行代码,I am a symbolic string constant.(即,将an换成a,将old-fashioned删除)70.第326页,“5.字符串数组”上面的一句,如果打算修改字符串,就不要用指针指向字符串字面量;“5.字符串数组”下面的一句,创建一个字符数组通常很方便(即将“如果”删除,将“会”换成通常)。

71.第332页,最后一段的第1句,fgets( )函数返回指向char的指针。

72.第336页,图11.3中“输入语句”栏,将这三个均修改为scanf(“%5s”,name);73.第348页,正文倒数第2段,并编写一个函数把输入的内容都转换成大写74.第356页,正文最后一段的第1句,程序清单11.28中的程序用s printf( )把3个项75.第358页,第一行,该函数返回指向s字符串首次出现的c字符的指针76.第366页,正文第3段,如果字符串仅以整数开头,at oi()函数也能处理77.第370页,第5题的e项,如果用*pc--替换*--pc,会打印什么78.第371页,“11.13编程练习”第1题,从输入中获取n个字符(即将“下”删除)79.第372页,第8题,如果第2个字符串包含在第1个字符串中;第10题,该程序应该应用该函数读取每个输入的字符串,并显示处理后的结果;第11题,编写一个程序80.第374页,第2段,内含这些字符值的字符串字面量就是一个对象,由于字符串字面量中的每个字符都能被……81.第382页,“12.1.7外部链接的静态变量”第3行,放在所有函数的外面(即将其中一个“在”删除)82.第383页,正文最后一段第2行,外部变量Hocus对main()和magic()均不可见83.第391页,正文第1段,在这个文件中不要求写出该函数定义。

相关文档
最新文档