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;}(注:可编辑下载,若有不当之处,请指正,谢谢!)。

C Primer Plus第六版中文版习题答案

C Primer Plus第六版中文版习题答案

C Primer Plus第六版中文版习题答案Github: https:///zhayujie/C-Primer-PlusEmail: yjzha1996@第一章1.#include <stdio.h>int main(void) {double inch, cm;printf("Please input the inches: ");scanf("%lf", &inch);cm = inch * 2.54;printf("%g cm\n", cm);return 0;}第二章3.#include<stdio.h>int main(void){int days,years=21;days=years*365;printf("我年龄是%d岁,%d天\n",years,days);return 0;}4.#include<stdio.h>void jolly(void);void deny(void);int main(void)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");}5.#include<stdio.h>void br(void);void ic(void);int main(void){br();printf(",");ic();printf("\n");ic();printf("\n");br();printf("\n");return 0;}void br(void){printf("Brazil,Russia");}void ic(void){printf("India,China");}#include<stdio.h>int main(void){int toes=10;int toes_2,toes2;toes_2=2*toes;toes2=toes*toes;printf("toes是%d,toes的两倍是%d,toes的平方是%d\n",toes,toes_2,toes2); return 0;}8.#include<stdio.h>void one_three(void);void two(void);int main(void){printf("starting now\n");one_three();}void one_three(void){printf("one\n");two();printf("three\n")printf("done!\n")}void two(void){printf("two\n");}第三章2.#include<stdio.h>int main(void){char ch;printf("please input a number:");scanf("%d",&ch);printf("%c\n",ch);return 0;}4.#include<stdio.h>int main(void){float a;printf("Enter a floating-point value: ");scanf("%f",&a);printf("fixed-point notation: %f\n",a);printf("exponential notation: %e\n",a);return 0;}5.#include<stdio.h>int main(void){int age;double seconds;printf("please input your age: ");scanf("%d",&age);seconds=age*3.156e7;printf("the corresponding seconds are: %e\n",seconds);return 0;}7.#include<stdio.h>int main(void){float inches,cms;printf("input your height(inch): ");scanf("%f",&inches);cms=inches*2.54;printf("your height(cm): %f\n",cms);return 0;}8.#include<stdio.h>int main(void){float pint,ounce,soupspoon,teaspoon,cup;printf("input the number of cups: ");scanf("%f",&cup);pint=cup/2;ounce=cup*8;soupspoon=ounce*2;teaspoon=soupspoon*3;printf("they are equivalent of:\n%f pint\n%f ounce\n%f soupspoons\n%f teaspoons\n",pint,ounce,soupspoon,teaspoon);return 0;}第四章1.#include<stdio.h>int main(void){char firstname[40],lastname[40];printf("Input your firstname: ");scanf("%s",firstname);printf("Input your lastname: ");scanf("%s",lastname);printf("Your name is %s,%s\n",firstname,lastname);return 0;}2.#include<stdio.h>#include<string.h>int main(void){char name[40];int width;printf("Input your name: ");scanf("%s",name);width=strlen(name)+3;printf("%*s\n",width,name); //输入的名和姓中间不能分隔return 0;}4.#include<stdio.h>int main(void){float height;char name[40];printf("Input your height(cm) and name: ");scanf("%f%s",&height,name);height=height/100;printf("%s, you are %.3fm tall\n",name,height);return 0;}5.#include<stdio.h>int main(void){float speed,size,time;printf("Input the download speed(Mb/s) and the file size(MB):\n"); scanf("%f%f",&speed,&size);time=size/speed*8.0;printf("At %.2f megabits per second, a file of %.2f megabytes\n",speed,size);printf("downloads in %.2f seconds.\n",time);return 0;}6.#include<stdio.h>#include<string.h>int main(void){char firstname[40],lastname[40];printf("Input your firstname: ");scanf("%s",firstname);printf("Input your lastname: ");scanf("%s",lastname);printf("%s %s\n",firstname,lastname);printf("%*d %*d\n",strlen(firstname),strlen(firstname),strlen(lastname),strlen(lastname)); printf("%s %s\n",firstname,lastname);printf("%*d %*d\n",-strlen(firstname),strlen(firstname),-strlen(lastname),strlen(lastname) );return 0;}7.#include<stdio.h>#include<float.h>int main(void){double a=1.0/3.0;float b=1.0/3.0;printf("%.6f %.6f\n",a,b); //左侧double型右侧float型printf("%.12f, %.12f\n",a,b);printf("%.16f, %.16f\n",a,b);printf("DBL_DIG: %d\n",DBL_DIG);printf("FLT_DIG: %d\n",FLT_DIG);return 0;}8.#include<stdio.h>#define GALLON 3.758 //1 gallon=3.785 liters#define MILE 1.609 //1 mile=1.609 kilometersint main(void){float gallon,mile;printf("Input miles and gallons: ");scanf("%f%f",&mile,&gallon);printf("Miles per gallon: %.1f\n",mile/gallon);printf("Litre per 100 kilometers: %.1f\n",gallon*GALLON/(mile*MILE)*100);return 0;}第五章1.#include<stdio.h>#define H_P_M 60 //1h=60minint main(void){int hour,min,left;printf("Enter the number of minutes: ");scanf("%d",&min);while(min>0){hour=min/H_P_M;left=min%H_P_M;printf("%d minutes is %d hours and %d minutes.\n",min,hour,left); printf("Enter your next value: ");scanf("%d",&min);}printf("Good bye!\n");return 0;}2.#include<stdio.h>int main(void){int num,count;printf("Input a integer: ");scanf("%d",&num);count=0;while(count++<11){printf("%d ",num);num++;}printf("\n");return 0;}3.#include<stdio.h>#define DAYS_PER_WEEK 7 //一周7天int main(void){int day,week,left;printf("Input the number of days: ");scanf("%d",&day);while(day>0){week=day/DAYS_PER_WEEK;left=day%DAYS_PER_WEEK;printf("%d days are %d weeks, %d days.\n",day,week,left); printf("Next input: ");scanf("%d",&day);}return 0;}4.#include<stdio.h>#define CM_PER_FEET 30.48 //1feet=30.48cm#define CM_PER_INCH 2.54 //1inch=2.54cmint main(void){int feet;float cm,inch;printf("Enter a height in centimeters: ");scanf("%f",&cm);while(cm>0){feet=(int)(cm/CM_PER_FEET);inch=(cm-feet*CM_PER_FEET)/CM_PER_INCH;printf("%.1f cm = %d feet, %.1f inches\n",cm,feet,inch); printf("Enter a height in centimeters (<=0 to quit): "); scanf("%f",&cm);}printf("bye\n");return 0;}5.#include<stdio.h>int main(void){int count,sum,days;printf("Input the number of days: ");scanf("%d",&days);count=sum=0;while(count++<days)sum=sum+count;printf("The money you earned: %d\n",sum);return 0;}6.#include<stdio.h>int main(void){int count,sum,days;printf("Input the number of days: ");scanf("%d",&days);count=sum=0;while(count++<days)sum=sum+count*count;printf("The money you earned: %d\n",sum);return 0;}7.#include<stdio.h>void cube(double n);int main(void){double num;printf("Input a number: ");scanf("%lf",&num);cube(num);}void cube(double n){printf("The cube of %f is %f\n",n,n*n*n);}8.#include<stdio.h>int main(void){int num1,num2;printf("This program computes moduli.\n");printf("Enter an integer to serve as the second operand: ");scanf("%d",&num1);printf("Now enter the first operand: ");scanf("%d",&num2);while(num2>0){printf("%d %% %d is %d\n",num2,num1,num2%num1);printf("Enter next number for first operand (<= 0 to quit): "); scanf("%d",&num2);}printf("Done\n");}9.#include<stdio.h>void Temperatures(double fah);int main(void){double fah,cel,kel;//华氏温度,摄氏温度,开氏温度printf("Input the Fahrenheit temperature: ");while(scanf("%lf",&fah)==1)Temperatures(fah);printf("Next input: ");}printf("Done.\n");}void Temperatures(double fah){const double a=5.0,b=9.0,c=32.0,d=276.13; printf("%.2f ℉ is %.2f ℃, %.2f K.\n",fah,a/b*(fah-c),a/b*(fah-c)+d);}第六章1.#include<stdio.h>#define SIZE 26int main(void){char ch[SIZE];int index;for(index=0;index<SIZE;index++){ch[index]='a'+index;printf("%c ",ch[index]);}printf("\n");return 0;}2.#include<stdio.h>int main(void){int i,j;for(i=1;i<=5;i++)for(j=1;j<=i;j++)printf("$");printf("\n");}return 0;}3.#include<stdio.h>int main(void){int i,j;for(i=1;i<=6;i++){for(j=0;j<i;j++)printf("%c",'F'-j); printf("\n");}return 0;}4.#include<stdio.h>#define ROWS 6int main(void){char ch;int i,j;for(ch='A',i=0;i<ROWS;i++) {for(j=0;j<=i;j++)printf("%c",ch++); printf("\n");}return 0;}5.#include<stdio.h>#define ROWS 5int main(void){char ch='A';int i,j;for(i=1;i<=ROWS;i++){for(j=1;j<=ROWS-i;j++)printf(" ");for(j=0;j<i;j++)printf("%c",ch+j);for(j=i-2;j>=0;j--)printf("%c",ch+j);printf("\n");}return 0;}6.#include<stdio.h>int main(void){int max,min,num;printf("Input the min and max: ");scanf("%d%d",&min,&max);printf("%10s%10s%10s\n","number","square","cube");for(num=min;num<=max;num++)printf("%10d%10d%10d\n",num,num*num,num*num*num); return 0;}7.//与题目不同打印的是句子#include<stdio.h>#include<string.h>#define SIZE 40int main(void){int i,index=-1;char ch[SIZE];printf("Input a word: ");do{ index++;scanf("%c",&ch[index]);}while(ch[index]!='\n');for(i=index+1;i<=40;i++)ch[i]='\0';for(index=strlen(ch);index>=0;index--)printf("%c",ch[index]);printf("\n");return 0;}8.#include<stdio.h>int main(void){double n1,n2;printf("Input two numbers: ");while(2==scanf("%lf%lf",&n1,&n2)){printf("%f\n",(n1-n2)/n1*n2);printf("Input your next pair of numbers: ");}printf("Bye!\n");return 0;}9.#include<stdio.h>double calculate(double n1, double n2);int main(void){double num1, num2;printf("Input two numbers: ");while (2 == scanf("%lf%lf", &num1, &num2)) //输入两个浮点数 {printf("%f\n", calculate(num1, num2)); //函数调用printf("Input your next pair of numbers: ");}printf("Bye!\n");return 0;}double calculate(double n1, double n2){return ((n1 - n2) / (n1 * n2)); //返回运算结果}10.#include <stdio.h>int main(void){int lower, upper;int num, sum;printf("Enter lower and upper integer limits: ");scanf("%d%d", &lower, &upper);while (lower < upper){for (sum=0, num=lower; num <= upper; num++)sum = sum + num * num; //计算平方和printf("The sums of the squares from %d to %d is %d\n", lower * lower, upper * upper, sum); //输出结果printf("Enter next set of limits: ");scanf("%d%d", &lower, &upper); //下一次输入}printf("Done\n");return 0;}11.#include <stdio.h>#define SIZE 8int main(void){int num[SIZE];int index;printf("Enter 8 integers: ");for (index=0; index<SIZE; index++) //输入8个整数scanf("%d", &num[index]);for (index=SIZE-1; index >= 0; index--) //倒序输出printf("%d ", num[index]);printf("\n");return 0;}12.#include <stdio.h>int main(void){double sum1=0, sum2=0;int count, items, sign;printf("Enter the items: ");scanf("%d", &items); //输入序列的项数for (count=1, sign=1; count <= items; count++, sign *= -1){sum1 += 1.0 / count;sum2 += 1.0 * sign / count;} //分别计算两序列的和 printf("1.0 + 1.0/2.0 + 1.0/3.0 + 1.0/4.0 + ... = %f\n", sum1); printf("1.0 - 1.0/2.0 + 1.0/3.0 - 1.0/4.0 + ... = %f\n", sum2);return 0;}13.#include <stdio.h>#define SIZE 8int main(void){int index, count, num[SIZE];for (index = 0, count = 1; index < SIZE; index++){count *= 2;num[index] = count;} //for循环将数组元素设为2的前8次幂index=0; //初始化index的值doprintf("%d ", num[index++]);while (index < SIZE); //do while循环显示数组元素的值printf("\n");return 0;}14.#include <stdio.h>#define SIZE 8int main(){double num1[SIZE], num2[SIZE];int index1, index2, index;printf("Enter 8 numbers to the first array:\n");for (index1 = 0; index1 < SIZE; index1++)scanf("%lf", &num1[index1]); //向第一个数组输入8个数 num2[0] = num1[0];for (index1 = 1, index2 = 1; index1 < SIZE; index1++, index2++) num2[index2] = num2[index2-1] + num1[index1];//为第二个数组赋值(是第一个数组对应的元素之和)printf("The first array: ");for (index=0; index < SIZE; index++) {printf("%6.2f", num1[index]);} //输出第一个数组的内容 printf("\nThe second array: ");for (index=0; index < SIZE; index++) {printf("%6.2f", num2[index]); //输出第二个数组的内容 }printf("\n");return 0;}15.#include <stdio.h>#include <string.h>#define SIZE 255int main(void){int index;char ch[SIZE];printf("Enter a line: ");for(index = 0, scanf("%c", &ch[0]); ch[index] != '\n';){index++;scanf("%c", &ch[index]);} //输入内容到字符数组中,回车时结束for(index += 1; index < SIZE; index++)ch[index] = '\0'; //将数组剩余空间补充为'\0'for(index = strlen(ch); index >=0; index--)printf("%c", ch[index]); //倒序输出内容printf("\n");return 0;}16.#include <stdio.h>#define RATE_DAPHNE 0.1#define RATE_DEIRDRE 0.05 //两人的利率#define MONEY 100int main(void){int year;double daphne = MONEY, deirdre = MONEY; //两人的初始投资额相同for (year = 1; daphne >= deirdre; year++){daphne += MONEY * RATE_DAPHNE;deirdre += deirdre * RATE_DEIRDRE;}//计算Deirdre投资额超过Daphne需要的年数和当时的金额printf("After %d year, Deirdre's investment will be more than Daphne's,\n""Daphne's investment will be $%lf,\nand Deirdre's investment will be $%lf.\n",year, daphne, deirdre); //输出结果return 0;}17.#include <stdio.h>#define INITIAL_MONEY 100 //账户初始金额为100万元#define ANNUAL_RATE 0.08 //年利率为8%int main(void){int year;double money;for(year = 1, money=INITIAL_MONEY; money>0; year++)money += money * ANNUAL_RATE - 10; //计算每年年终的账户余额printf("After %d years, Chuckie will draw all money from his account.\n", year);return 0;}18.#include <stdio.h>#define INITIAL_NUMBER 5 //初始朋友数为5人#define DUNBAR_NUMBER 150 //邓巴数int main(void){int week;int number = INITIAL_NUMBER;for (week = 1; number <= DUNBAR_NUMBER; week++){number = (number - week) * 2; //计算每周的朋友数量printf("After %d week, the number of Rabnud's friends is %d\n", week, number);}return 0;}第七章1.#include <stdio.h>int main(void){char ch;int n_space = 0; //空格数int n_newline = 0; //换行数int n_others = 0; //其他字符数printf("Enter some text; Enter # to quit.\n"); while ((ch = getchar()) != '#'){if (ch == ' ')n_space++;else if (ch == '\n')n_newline++;elsen_others++;}printf("Spaces: %d, newlines: %d, others: %d\n", n_space, n_newline, n_others);return 0;}2.#include <stdio.h>#define CHARS_PER_LINE 8 //每行字符数int main(void){char ch;int n_chars = 1; //字符数printf("Enter some characters(# to quit):\n"); while ((ch = getchar()) != '#'){printf("%3c(%3d) ", ch, ch);if (n_chars++ % CHARS_PER_LINE == 0)printf("\n");}printf("\n");return 0;}3.#include <stdio.h>int main(void){int num;int n_even = 0, n_odd = 0; //偶数和奇数个数int sum_even = 0, sum_odd = 0; //偶数和奇数和printf("Enter some integers(0 to quit):\n");scanf("%d", &num);while (num != 0){if (num % 2 == 0){n_even++;sum_even += num;} //计算偶数个数和偶数和else{n_odd++;sum_odd +=num;} //计算奇数个数和奇数和scanf("%d",&num);}printf("The number of even numbers is %d, ""and the everage of even numbers is %.2f\n",n_even, (n_even == 0) ? 0 : (float)sum_even / n_even); printf("The number of odd numbers is %d, ""and the everrage of odd numers is %.2f\n",n_odd, (n_odd == 0) ? 0 : (float)sum_odd / n_odd);return 0;}4.#include <stdio.h>int main(void){char ch;int n_repl = 0; //替换次数printf("Enter some texts(# to quit):\n");while ((ch = getchar()) != '#') {if (ch == '.'){ch = '!';n_repl++;} //替换句号else if (ch == '!'){printf("!");n_repl++;} //替换感叹号printf("%c", ch);}printf("\n%d substitutions were made.\n", n_repl);return 0;}5.#include <stdio.h>int main(void){char ch;int n_repl = 0; //替换次数printf("Enter some texts(# to quit):\n");while ((ch = getchar()) != '#') {switch (ch){case '.': ch = '!';n_repl++;break;case '!': printf("!");n_repl++;break;default: break;} //利用switch语句进行替换 printf("%c",ch);}printf("\n%d substitutions were made.\n", n_repl); return 0;}6.#include <stdio.h>int main(void){char ch;char last_ch = 0; //前一个字符int count=0;printf("Enter some texts(# to quit):\n");while ((ch = getchar()) != '#'){if ((ch == 'i') && (last_ch == 'e'))count++;last_ch = ch; //出现ei时,计数+1}printf("\"ei\" appeared %d times.\n", count);return 0;}7.#include <stdio.h>#define BASE 1000 //基本工资 100美元/h#define TIME 40 //超过40h为加班#define MUL 1.5 //加班时间算作平时的1.5倍#define RATE1 0.15 //前300美元的税率#define RATE2 0.2 //300-450美元的税率#define RATE3 0.25 //大于450美元的税率#define BREAK1 300 //税率的第一个分界点#define BREAK2 450 //税率的第二个分界点int main(void){double hour, tax, gross;printf("Input your work hours in a week: ");scanf("%lf", &hour);if (hour <= TIME)gross = hour * BASE;elsegross = TIME * BASE + (hour - TIME) * MUL * BASE;//计算总收入if (gross <= BREAK1)tax = gross * RATE1;else if (gross <= BREAK2)tax = BREAK1 * RATE1 + (gross - BREAK1) * RATE2;elsetax = BREAK1 * RATE1 + (BREAK2 - BREAK1) * RATE2+ (gross - BREAK2) * RATE3;//计算税金printf("Your gross income is $%.2lf\nYour tax is $%.2lf\n""Your net income is $%.2lf\n",gross, tax, (gross - tax));return 0;8.#include <stdio.h>#define BASE1 8.75#define BASE2 9.33#define BASE3 10.00#define BASE4 11.20//四种等级的基本工资#define TIME 40 //超过40h为加班#define MUL 1.5 //加班时间算作平时的1.5倍#define RATE1 0.15 //前300美元的税率#define RATE2 0.2 //300-450美元的税率#define RATE3 0.25 //大于450美元的税率#define BREAK1 300 //税率的第一个分界点#define BREAK2 450 //税率的第二个分界点int main(void){double base, hour, tax, gross;int count, num;const int LENGTH = 65; //*的长度printpart: for (count = 0; count < LENGTH; count++)printf("*");printf("\nEnter the number corresponding to the desired pay rate or action:\n");printf("%-36s%s","1) $8.75/hr", "2) $9.33/hr\n");printf("%-36s%s","3) $10.00/hr", "4) $11.20/hr\n");printf("%s\n", "5) quit");for (count = 0; count < LENGTH; count++)printf("*");printf("\n");//打印表格while (scanf("%d", &num) == 1) {switch (num){case 1: base = BASE1;break;case 2: base = BASE2;break;case 3: base = BASE3;break;case 4: base = BASE4;break;case 5: printf("quit.\n");return 0;default: printf("Please input the right option.\n");goto printpart;} //选择基本工资等级printf("Input your work hours in a week: ");scanf("%lf", &hour);if (hour <= TIME)gross = hour * base;elsegross = TIME * base + (hour - TIME) * MUL * base;//计算总收入if (gross <= BREAK1)tax = gross * RATE1;else if (gross <= BREAK2)tax = BREAK1 * RATE1 + (gross - BREAK1) * RATE2;elsetax = BREAK1 * RATE1 + (BREAK2 - BREAK1) * RATE2+ (gross - BREAK2) * RATE3;//计算税金printf("Your gross income is $%.2lf\nYour tax is $%.2lf\n" "Your net income is $%.2lf\n",gross, tax, (gross - tax));printf("\nYour next choice:\n");}return 0;}9.#include <stdio.h>int main(void){int div, prime;int num, count;int flag;printf("Input a positive integer: ");scanf("%d", &num);printf("The prime numbers in range:\n");for (prime = 2; prime <= num; prime++) //外层循环显示所有素数 {flag = 1;for (div = 2; (div * div) <= prime; div++){if (prime % div == 0)flag = 0;} //内层循环检验是否为素数 if (flag) //利用标记flag判断printf("%d ",prime);}printf("\n");return 0;}10.#include <stdio.h>#define RATE1 0.15#define RATE2 0.28#define SINGLE 17850 //单身人群的税率分界点#define HOST 23900 //户主人群的税率分界点#define MAR_SHA 29750 //已婚共有人群的分界点#define MAR_DEV 14875 //已婚离异人群的分界点int main(void){int num;double income, tax_break, tax;printpart: printf("Please enter Corresponding""figures to select the type\n");printf("1 single, 2 host, 3 married and shared, ""4 married but devoced and 5 to quit.\n");scanf("%d", &num);switch (num){case 1: tax_break = SINGLE;break;case 2: tax_break = HOST;break;case 3: tax_break = MAR_SHA;break;case 4: tax_break = MAR_DEV;break;case 5: printf("quit.\n");return 0;default: printf("Please input right number.");goto printpart; //回到输入阶段}printf("Enter your income: "); //指定种类和收入while (scanf("%lf", &income) == 1){if (income <= tax_break)tax = income * RATE1;elsetax = tax_break * RATE1 + (income - tax_break) * RATE2; //计算税金printf("The tax is $%.2lf.\n", tax);printf("Your next input: \n");goto printpart; //回到输入阶段}return 0;}11.#include <stdio.h>#include <ctype.h>#define ARTICHOKE 2.05 //洋蓟2.05美元/磅#define BEET 1.15 //甜菜1.15美元/磅#define CARROT 1.09 //胡萝卜1.09美元/磅#define DISCOUNT_LIMIT 100//包装费和运费打折要求订单100美元#define DISCOUNT_RATE 0.05 //折扣为%5#define BREAK1 5#define BREAK2 20 //装运费的分界点#define FEE1 6.5#define FEE2 14#define FEE3_RATE 0.5//不同重量区间的装运费,其中超过20磅的每续重一磅//增加0.5元int main(void){double weight;double weight_artichoke = 0;double weight_beet = 0;double weight_carrot = 0; //购买三种蔬菜的重量double total_weight; //总重量double veg_cost; //三种蔬菜总共花费double order_cost; //订单总额double total_cost; //费用总额double pack_tran_fee; //装运费double discount;int count = 0;char ch;printf("Please select the vegetables you want to buy:\n");printf("a: artichoke $%.2f/lb\n", ARTICHOKE);printf("b: beet $%.2f/lb\n", BEET);printf("c: carrot $%.2f/lb\n", CARROT);printf("q: quit.\n");//打印选择信息while ((ch = tolower(getchar())) != 'q'){// if (ch == '\n')// continue; //滤掉回车switch (ch){case 'a': printf("Input the weight of artichoke in pound: "); scanf("%lf", &weight);weight_artichoke += weight;count++;printf("Continue entering a, b, c or q: ");break;case 'b': printf("Input the weight of beet in pound: ");scanf("%lf", &weight);weight_beet += weight;count++;printf("Continue entering a, b, c or q: ");break;case 'c': printf("Input the weight of carrot in pound: ");scanf("%lf", &weight);weight_carrot += weight;count++;printf("Continue entering a, b, c or q: ");break;default: printf("Please enter the right character.");}while (getchar () != '\n')continue; //滤掉输入重量后面的所有字符}if (!count){printf("Bye.\n");return 0;} //开始输出q,直接退出total_weight = weight_artichoke + weight_beet + weight_carrot;veg_cost = weight_artichoke * ARTICHOKE + weight_beet * BEET+ weight_carrot * CARROT;discount = 0;if (veg_cost >= DISCOUNT_LIMIT){discount = veg_cost * DISCOUNT_RATE;order_cost = veg_cost - discount;}elseorder_cost = veg_cost; //折扣计算if (total_weight <= BREAK1)pack_tran_fee = FEE1;else if (total_weight <= BREAK2)pack_tran_fee = FEE2;elsepack_tran_fee = FEE2 + (total_weight - BREAK2) * FEE3_RATE;//装运费计算total_cost = order_cost + pack_tran_fee;printf("\nHere is what you choose:\n");if (weight_artichoke) {printf("artichoke Price: $%.2f/lb weight: %.2f pounds cost: $%.2f\n",ARTICHOKE, weight_artichoke, weight_artichoke * ARTICHOKE); }if (weight_beet) {printf("beet Price: $%.2f/lb weight: %.2f pounds cost:。

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

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

第二章:开始学习C++ n”;}<<endl; return 0;}double C2F(double t){return *t+32;}<<endl; return 0;}double convert(double t){return 63240*t;n"; return 0;}style(miles per gallon):"<<endl;cout<<Euro_style<<" L/100Km = "<<*Euro_style<<" mpg\n"; return 0;}Enter the automobile gasoline consumption figure inEuropean style(liters per 100kilometers): Converts to .style(miles per gallon):L/100Km = mpgPress any key to continuestyle(miles pergallon):"; doubleUS_style;cin>>US_style;cout<<"Converts to European style(miles per gallon):"<<endl; cout<<US_style<<" mpg = "<< *US_style<<"L/100Km\n"; return 0;}style(miles per gallon):19Converts to European style(miles per gallon): 19 mpg = 100KmPress any key to continue第四章复合类型n";return 0;}rand<<endl<<snack[i].weight<<endl<<snack[i].calory<<endl<<endl;}return 0;}rand="A";eight=;snack[0].calory=200;snack[1].brand="B";snack[1].weight=;snack[1].calory=400;snack[2].brand="C";snack[2].weight=;snack[2].calory=500;for(int i=0;i<3;i++){cout << " brand: " <<snack[i].brand << endl; cout<< " weight: " <<snack[i].weight << endl;cout << " calorie: " << snack[i].calory << endl<<endl;}delete []snack;return 0;}et(); car*ps=newcar[num];for(int i=0;i<num;++i){cout<<"Car #"<<i+1<<":\n";cout<<"Please enter themake: ";getline(cin,ps[i].name);cout<<"Please enter theyear made: ";(cin>>ps[i].year).get();}cout<<"Here is yourcollection:\n"; for(int i=0;i<num;++i)cout<<ps[i].year<<""<<ps[i].name<<endl; delete [] ps;return 0;}#include <iostream>#include<string> usingnamespace std;struct car{string maker;int year;};int main(){int number;cout << "How many cars do you wish to catalog "; cin >> number;car* a = new car[number];for (int i = 0; i < number; i++){cout << "Car #" << i+1 << ": " <<endl; cout << "Please enter themaker: "; ();getline(cin,a[i].maker);cout << "Please enter the yearmade: "; cin >> a[i].year;}cout << "Here is your collection: "<< endl; for (int i = 0; i < number;i++)cout << a[i].year << " " << a[i].maker <<endl; delete [] a;return 0;}#include<iostream> usingnamespace std;struct car{charmaker[20];int year;};int main(){int number;cout << "How many cars do you wish to catalog "; cin >> number;car* a = new car[number];for (int i = 0; i < number; i++){cout << "Car #" << i+1 << ": " <<endl; cout << "Please enter themaker: "; ();(a[i].maker, 20);cout << "Please enter the yearmade: "; cin >> a[i].year;}cout << "Here is your collection: "<< endl; for (int i = 0; i < number;i++)cout << a[i].year << " " << a[i].maker <<endl; delete [] a;return 0;}n"; return 0;}n";return 0;}和的区别是:word != "done",因为当 word = done 一样时,返回值为1,不一样时才是返回0.;for(intk=0;k<=i;++k)cout<<"*";cout<<endl;}return 0;}第六章分支语句和逻辑运算符n"; break;case 'p':cout<<"A maple is apianist.\n"; break;case 't':cout<<"A maple is atree.\n"; break;case 'g':cout<<"A maple is a game.\n";}return0;}#include<iostream> usingnamespace std;void show();int main(){show();char choice;while (cin >> choice){switch(choice){case 'c' : cout << "It's acarnivore.\n"; break;case 'p' : cout << "It's apianist.\n"; break;case 't' : cout << "A maple is atree.\n"; break;case 'g' : cout << "It's agame.\n"; break;default : cout << "Please enter a c, p, t, org:";}}return 0;}void show(){cout << "Please enter one of the followingchoices: \n" "c) carnivore p)pianist\n""t) tree g) game\n";}display by name b. display by title\n"<<"c. display by bopname d. diplay bypreference\n"<<"q.quit\n";char ch;bop member[5]={{"Wimp Macho","EnglishTeacher","DEMON",0},{"Raki Rhodes","JuniorProgrammer","BOOM",1},{"Celia Laiter","Super Star","MIPS",2},{"Hoppy Hipman","AnalystTrainee","WATEE",1},{"Pat Hand","Police","LOOPY",2}};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; elseif(member[i].preference==1)cout<<member[i].title<<endl; elseif(member[i].preference==2)cout<<member[i].bopname<<endl;}break;}cout<<"Next choice: ";}cout<<"Bye!\n";return 0;}#include <iostream> using namespace std; const int strsize = 30; struct bop{charfullname[strsize];chartitle[strsize];charbopname[strsize];int preference;};void show();int main(){bop A[5] ={{"Wimp Macho", "Teacher", "HAHA", 0},{"Raki Rhodes", "Junior Programmer", "LIAR",1},{"Celia", "engineer", "MIPS", 2},{"Hoppy Hipman", "Analyst Trainee", "WAHU", 1},{"Pat Hand", "Student", "LOOPY", 2}};cout << "Benevolent Order of ProgrammersReport\n"; show();cout << "Enter yourchoice: "; char choice;cin >> choice;while (choice != 'q'){switch(choice){case 'a' : cout << A[0].fullname << endl << A[1].fullname << endl<< A[2].fullname << endl << A[3].fullname<< endl<< A[4].fullname <<endl; break;case 'b' : cout << A[0].title << endl << A[1].title<< endl<< A[2].title << endl << A[3].title<< endl<< A[4].title <<endl; break;case 'c' : cout << A[0].bopname << endl << A[1].bopname << endl<< A[2].bopname << endl << A[3].bopname<< endl<< A[4].bopname <<endl; break;case 'd' : cout << A[0].fullname << endl << A[1].title << endl<< A[2].bopname << endl << A[3].title <<endl<< A[4].bopname <<endl; break;default : cout << "That's not the properchoice.\n";}cout << "Next choice:"; cin >> choice;}cout <<"Bye!\n";return 0;}void show(){cout << "a. display by name b. display by title\n"<< "c. display by bopname d. display bypreference\n"<< "q. quit\n";}ame); cout<<"请输入第"<<i+1<<"位捐款人捐款的数目:";cin>>ps[i].money;();}cout<<"GrandPatrons:\n"; for(inti=0;i<num;++i)if(ps[i].money>10000){cout<<ps[i].name<<"\n"<<ps[i].money<<endl;++temp;}if(temp==0)cout<<"none\n";cout<<"Patrons:\n"; for(inti=0;i<num;++i)if(ps[i].money<=10000){cout<<ps[i].name<<"\n"<<ps[i].money<<endl;++temp;}if(temp==0)cout<<"none\n";delete []ps; return0;}#include <iostream>#include<string> usingnamespace std;struct charity{string name;double money;};int main(){int number;int count =0;cout << "Please enter the number ofdonator: "; cin >> number;charity *pt = newcharity[number]; for (int i= 0; i < number; i++){cout << "Please enter yourname: "; ();getline(cin, pt[i].name);cout << "Please enter the money you are going todonate: "; cin >> pt[i].money;if(pt[i].money >10000) count++;}if(count == 0)cout << "None(money >10000)"; else{cout << "Grand Patron\n";for(int i = 0; i < number;i++){if(pt[i].money > 10000)cout << pt[i].name << " " << pt[i].money<< endl;}}cout << endl;if(10 - count == 0)cout << "None(money <10000)"; else{cout << "Patron\n";for(int i = 0; i < number; i++){if(pt[i].money < 10000)cout << pt[i].name << " " << pt[i].money<< endl;}}return 0;}n"; exit(EXIT_FAILURE);}inFile>>ch;while()){++sum;inFile>>ch;}if())cout<<"End of filereached.\n"; else if())cout<<"Input terminated by datamismatch.\n"; elsecout<<"Input terminated for unkonwn reason.\n";cout<<"总共有"<<sum<<"个字符在这个文件中。

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

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

第二章:开始学习C++//ex2.1--display your name and address#include<iostream>int main(void){using namespace std;cout<<"My name is liao chunguang and I live in hunan chenzhou.\n”;}//ex2.2--convert the furlong units to yard uints-把浪单位换位码单位#include<iostream>double fur2yd(double);int main(){using namespace std;cout<<"enter the distance measured by furlong units:";double fur;cin>>fur;cout<<"convert the furlong to yard"<<endl;double yd;yd=fur2yd(fur);cout<<fur<<" furlong is "<<yd<<" yard"<<endl;return 0;}double fur2yd(double t){return 220*t;}//ex2.3-每个函数都被调用两次#include<iostream>void mice();void see();using namespace std;int main(){mice();mice();see();see();return 0;}void mice(){cout<<"three blind mice"<<endl;}void see(){cout<<"see how they run"<<endl;}//ex2.4#include<iostream>int main(){using namespace std;cout<<"Enter your age:";int age;cin>>age;int month;month=age*12;cout<<age<<" years is "<<month<<" months"<<endl;return 0;}//ex2.5---convert the Celsius valve to Fahrenheit value#include<iostream>double C2F(double);int main(){using namespace std;cout<<"please enter a Celsius value:";double C;cin>>C;double F;F=C2F(C);cout<<C<<" degrees Celsius is "<<F<<" degrees Fahrenheit."<<endl;return 0;}double C2F(double t){return 1.8*t+32;}//ex2.6---convert the light years valve to astronomical units--把光年转换为天文单位#include<iostream>double convert(double);//函数原型int main(){using namespace std;cout<<"Enter the number of light years:";double light_years;cin>>light_years;double astro_units;astro_units=convert(light_years);cout<<light_years<<" light_years = "<<astro_units<<" astronomical units."<<endl; return 0;}double convert(double t){return 63240*t;//1 光年=63240 天文单位}//ex2.7--显示用户输入的小时数和分钟数#include<iostream>void show();main(){using namespace std;show();return 0;}void show(){using namespace std;int h,m;cout<<"enter the number of hours:";cin>>h;cout<<"enter the number of minutes:";cin>>m;cout<<"Time:"<<h<<":"<<m<<endl;}第三章:处理数据//ex3.1—将身高用英尺(feet)和英寸(inch)表示#include<iostream>const int inch_per_feet=12;// const 常量--1feet=12inches--1 英尺=12 英寸int main(){using namespace std;cout<<"please enter your height in inches:___\b\b\b";// \b 表示为退格字符int ht_inch;cin>>ht_inch;int ht_feet=ht_inch/inch_per_feet;//取商int rm_inch=ht_inch%inch_per_feet;//取余cout<<"your height is "<<ht_feet<<" feet,and "<<rm_inch<<" inches\n";return 0;}//ex3.2--计算相应的body mass index〔体重指数〕#include<iostream>const int inch_per_feet=12;const double meter_per_inch=0.0254;const double pound_per_kilogram=2.2;int main(){using namespace std;cout<<"Please enter your height:"<<endl;cout<<"First,enter your height of feet part〔输入你身高的英尺部分〕:_\b"; int ht_feet;cin>>ht_feet;cout<<"Second,enter your height of inch part〔输入你身高的英寸部分〕:_\b"; int ht_inch;cin>>ht_inch;cout<<"Now,please enter your weight in pound:___\b\b\b";double wt_pound;cin>>wt_pound;int inch;inch=ht_feet*inch_per_feet+ht_inch;double ht_meter;ht_meter=inch*meter_per_inch;double wt_kilogram;wt_kilogram=wt_pound/pound_per_kilogram;cout<<endl;cout<<"Your pensonal body information as follows:"<<endl;cout<<"身高:"<<inch<<"(英尺inch)\n"<<"身高:"<<ht_meter<<"(米meter)\n"<<"体重:"<<wt_kilogram<<"(千克kilogram)\n";double BMI;BMI=wt_kilogram/(ht_meter*ht_meter);cout<<"your Body Mass Index(体重指数) is "<<BMI<<endl;return 0;}//ex3.3 以度,分,秒输入,以度输出#include<iostream>const int minutes_per_degree=60;const int seconds_per_minute=60;int main(){using namespace std;cout<<"Enter a latitude in degrees,minutes,and seconds:\n";cout<<"First,enter the degrees:";int degree;cin>>degree;cout<<"Next,enter the minutes of arc:";int minute;cin>>minute;cout<<"Fianlly,enter the seconds of arc:";int second;cin>>second;double show_in_degree;show_in_degree=(double)degree+(double)minute/minutes_per_degree+(double)second/mi nutes_per_degree/seconds_per_minute;cout<<degree<<" degrees,"<<minute<<" minutes,"<<second<<"seconds="<<show_in_degree<<" degrees\n";return 0;}//ex3.4#include<iostream>const int hours_per_day=24;const int minutes_per_hour=60;const int seconds_per_minute=60;int main(){using namespace std;cout<<"Enter the number of seconds:";long seconds;cin>>seconds;int Day,Hour,Minute,Second;Day=seconds/seconds_per_minute/minutes_per_hour/hours_per_day;Hour=seconds/seconds_per_minute/minutes_per_hour%hours_per_day;Minute=seconds/seconds_per_minute%minutes_per_hour;Second=seconds%seconds_per_minute;cout<<seconds<<"seconds = "<<Day<<" days,"<<Hour<<" hours,"<<Minute<<" minutes,"<<Second<<" seconds\n";return 0;}//ex3.5#include<iostream>int main(){using namespace std;cout<<"Enter the world population:";long long world_population;cin>>world_population;cout<<"Enter the population of the US:";long long US_population;cin>>US_population;double percentage;percentage=(double)US_population/world_population*100;cout<<"The population of the US is "<<percentage<<"% of the world population.\n"; return 0;}//ex3.6 汽车耗油量-美国(mpg)or 欧洲风格(L/100Km)#include<iostream>int main(){using namespace std;cout<<"Enter the miles of distance you have driven:";double m_distance;cin>>m_distance;cout<<"Enter the gallons of gasoline you have used:";double m_gasoline;cin>>m_gasoline;cout<<"Your car can run "<<m_distance/m_gasoline<<" miles per gallon\n";cout<<"Computing by European style:\n";cout<<"Enter the distance in kilometers:";double k_distance;cin>>k_distance;cout<<"Enter the petrol in liters:";double k_gasoline;cin>>k_gasoline;cout<<"In European style:"<<"your can used "<<100*k_gasoline/k_distance<<" liters of petrol per 100 kilometers\n";return 0;}//ex3.7 automobile gasoline consumption-耗油量--欧洲风格(L/100Km)转换成美国风格(mpg) #include<iostream>int main(){using namespace std;cout<<"Enter the automobile gasoline consumption figure in\n"<<"European style(liters per 100 kilometers):";double Euro_style;cin>>Euro_style;cout<<"Converts to U.S. style(miles per gallon):"<<endl;cout<<Euro_style<<" L/100Km = "<<62.14*3.875/Euro_style<<" mpg\n";return 0;}// Note that 100 kilometers is 62.14 miles, and 1 gallon is 3.875 liters.//Thus, 19 mpg is about 12.4 L/100Km, and 27 mpg is about 8.7 L/100Km.Enter the automobile gasoline consumption figure inEuropean style(liters per 100 kilometers):12.4Converts to U.S. style(miles per gallon):12.4 L/100Km = 19.4187 mpgPress any key to continue// ex3.7 automobile gasoline consumption-耗油量--美国风格(mpg)转换成欧洲风格(L/100Km)#include<iostream>int main(){using namespace std;cout<<"Enter the automobile gasoline consumption figure in\n"<<"U.S. style(miles per gallon):";double US_style;cin>>US_style;cout<<"Converts to European style(miles per gallon):"<<endl;cout<<US_style<<" mpg = "<< 62.14*3.875/US_style<<"L/100Km\n";return 0;}// Enter the automobile gasoline consumption figure inU.S. style(miles per gallon):19Converts to European style(miles per gallon):19 mpg = 12.6733L/100KmPress any key to continue第四章复合类型//ex4.1 display the information of student#include<iostream>const int Asize=20;using namespace std;struct student//定义结构描述{char firstname[Asize];char lastname[Asize];char grade;int age;};void display(student);//函数原型放在结构描述后int main(){cout<<"what is your first name?"<<endl;student lcg;//创建结构变量〔结构数据对象〕cin.getline(lcg.firstname,Asize);cout<<"what is your last name?"<<endl;cin.getline(stname,Asize);cout<<"what letter grade do you deserve?"<<endl;cin>>lcg.grade;cout<<"what is your age?"<<endl;cin>>lcg.age;display(lcg);return 0;}void display(student name){cout<<"Name: "<<name.firstname<<","<<stname<<endl;cout<<"Grade:"<<char(name.grade+1)<<endl;cout<<"Age:"<<name.age<<endl;}//ex4.2 use the string-class instead of char-array#include<iostream>#include<string>int main(){using namespace std;string name,dessert;cout<<"Enter your name: \n";getline(cin,name);cout<<"Enter your favorite dessert: \n";getline(cin,dessert);cout<<"I have some delicious "<<dessert;cout<<" for you, "<<name<<".\n";return 0;}//有时候会遇到需要按下两次回车键才能正确的显示结果,这是vc++6.0 的一个BUG,更改如下:else if (_Tr::eq((_E)_C, _D)){_Chg = true;_I.rdbuf()->sbumpc();//修改后的break; }ex4.3 输入其名和姓,并组合显示#include<iostream>#include<cstring>const int Asize=20;int main(){using namespace std;char fname[Asize];char lname[Asize];char fullname[2*Asize+1];cout<<"Enter your first name:";//输入名字,存储在fname[]数组中cin.getline(fname,Asize);cout<<"Enter your last name:";//输入姓,存储在lname[]数组中cin.getline(lname,Asize);strncpy(fullname,lname,Asize);//把姓lname 复制到fullname 空数组中strcat(fullname,", ");//把“,”附加到上述fullname 尾部strncat(fullname,fname,Asize);//把fname 名字附加到上述fullname 尾部fullname[2*Asize]='\0';//为防止字符型数组溢出,在数组结尾添加结束符cout<<"Here's the information in a single string:"<<fullname<<endl;//显示组合结果return 0;}#define _CRT_SECURE_NO_WARNINGS#include <iostream>#include <cstring>const int Asize = 20;int main(){using namespace std;char firstname[Asize];char lastname[50];cout << "Enter your first name: ";cin.getline(firstname,Asize);cout << "Enter your last name: ";cin.getline(lastname,50);strcat(lastname,", ");strncat(lastname,firstname,Asize);cout << "Here's the information in a single string: "<< lastname <<endl;return 0;}//ex4.4 使用string 对象存储、显示组合结果#include<iostream>#include<string>int main(){using namespace std;string fname,lname,attach,fullname;cout<<"Enter your first name:";getline(cin,fname);//note:将一行输入读取到string 类对象中使用的是getline(cin,str) //它没有使用句点表示法,所以不是类方法cout<<"Enter your last name:";getline(cin,lname);attach=", ";fullname=lname+attach+fname;cout<<"Here's the information in a single string:"<<fullname<<endl;return 0;}//ex4.5 declare a struct and initialize it 声明结果并创建一个变量#include<iostream>const int Asize=20;struct CandyBar{char brand[Asize];double weight;int calory;};int main(){using namespace std;CandyBar snack={"Mocha Munch",2.3,350};cout<<"Here's the information of snack:\n";cout<<"brand:"<<snack.brand<<endl;cout<<"weight:"<<snack.weight<<endl;cout<<"calory:"<<snack.calory<<endl;return 0;}//ex4.6 结构数组的声明及初始化#include<iostream>const int Asize=20;struct CandyBar{char brand[Asize];double weight;int calory;};int main(){using namespace std;CandyBar snack[3]={{"Mocha Munch",2.3,350},{"XuFuJi",1.1,300},{"Alps",0.4,100}};for(int i=0;i<3;i++)//利用for 循环来显示snack 变量的内容{cout<<snack[i].brand<<endl<<snack[i].weight<<endl<<snack[i].calory<<endl<<endl;}return 0;}//ex4.7 pizza 披萨饼#include<iostream>#include<string>const int Size=20;struct pizza//声明结构{char company[Size];double diameter;double weight;};int main(){using namespace std;pizza pie;//创建一个名为pie 的结构变量cout<<"What's the name of pizza company:";cin.getline(pie pany,Size);cout<<"What's the diameter of pizza:";cin>>pie.diameter;cout<<"What's the weight of pizza:";cin>>pie.weight;cout<<"company:"<<pie pany<<endl;cout<<"diameter:"<<pie.diameter<<"inches"<<endl;cout<<"weight:"<<pie.weight<<"ounches"<<endl;return 0;}//ex4.8 pizza pie 披萨饼使用new 创建动态结构#include<iostream>#include<string>const int Size=20;struct pizza//声明结构{char company[Size];double diameter;double weight;};int main(){using namespace std;pizza *pie=new pizza;//使用new 创建动态结构cout<<"What's the diameter of pizza:";cin>>pie->diameter;cin.get();//读取下一个字符cout<<"What's the name of pizza company:";cin.get(pie->company,Size);cout<<"What's the weight of pizza:";cin>>pie->weight;cout<<"diameter:"<<pie->diameter<<" inches"<<endl;cout<<"company:"<<pie->company<<endl;cout<<"weight:"<<pie->weight<<" ounches"<<endl;delete pie;//delete 释放内存return 0;}//ex.4.9 使用new 动态分配数组—方法1#include<iostream>#include<string>using namespace std;struct CandyBar{string brand;double weight;int calory;};int main(){CandyBar *snack= new CandyBar[3];snack[0].brand="A";//单个初始化由new 动态分配的内存snack[0].weight=1.1;snack[0].calory=200;snack[1].brand="B";snack[1].weight=2.2;snack[1].calory=400;snack[2].brand="C";snack[2].weight=4.4;snack[2].calory=500;for(int i=0;i<3;i++){cout << " brand: " << snack[i].brand << endl;cout << " weight: " << snack[i].weight << endl;cout << " calorie: " << snack[i].calory << endl<<endl;}delete [] snack;return 0;}//ex.4.10 数组—方法1#include <iostream>int main(){using namespace std;const int Size = 3;int success[Size];cout<<"Enter your success of the three times 40 meters running:\n"; cin >> success[0]>>success[1]>>success[2];cout<<"success1:"<<success[0]<<endl;cout<<"success2:"<<success[1]<<endl;cout<<"success3:"<<success[2]<<endl;double average=(success[0]+success[1]+success[2])/3;cout<<"average:"<<average<<endl;return 0;}//ex.4.10 array—方法2#include <iostream>#include <array>int main(){using namespace std;array<double,4>ad={0};cout<<"Enter your success of the three times 40 meters running:\n"; cin >> ad[0]>>ad[1]>>ad[2];cout<<"success1:"<<ad[0]<<endl;cout<<"success2:"<<ad[1]<<endl;cout<<"success3:"<<ad[2]<<endl;ad[3]=(ad[0]+ad[1]+ad[2])/3;cout<<"average:"<<ad[3]<<endl;return 0;}第五章循环和关系表达式//ex.5.1#include <iostream>int main(){using namespace std;cout<<"Please enter two integers: ";int num1,num2;cin>>num1>>num2;int sum=0;for(int temp=num1;temp<=num2;++temp)//or temp++sum+=temp;cout<<"The sum from "<<num1<<" to "<<num2<<" is "<<sum<<endl; return 0;}//ex.5.2#include <iostream>#include<array>int main(){using namespace std;array<long double,101>ad={0};ad[1]=ad[0]=1L;for(int i=2;i<101;i++)ad[i]=i*ad[i-1];for(int i=0;i<101;i++)cout<<i<<"! = "<<ad[i]<<endl;return 0;}#include <iostream>#include <array>using namespace std;int main(){array<long double, 101> multiply;multiply[0] = multiply[1] = 1LL;for (int i = 2; i <= 100; i++)multiply[i] = multiply[i-1]*i;cout << multiply[100];return 0;}//ex.5.3#include <iostream>int main(){using namespace std;cout<<"Please enter an integer: ";int sum=0,num;while((cin>>num)&&num!=0){sum+=num;cout<<"So far, the sum is "<<sum<<endl;cout<<"Please enter an integer: ";}return 0;}//ex.5.4#include <iostream>int main(){using namespace std;double sum1,sum2;sum1=sum2=0.0;int year=0;while(sum2<=sum1){++year;sum1+=10;sum2=(100+sum2)*0.05+sum2;}cout<<"经过"<<year<<"年后,Cleo 的投资价值才能超过Daphne 的投资价值。

C语言程序设计勘误表

C语言程序设计勘误表

C语言程序设计勘误表C语言程序设计勘误表说明:红色为修改后的字符。

1、p16原文:大写字母O的二进制编码依次是:0x1f,0x24,0x42, 0x42, 0x42, 0x42, 0x24, 0x1f。

中国的“中”字的二进制编码的按照从上到下,从左到右顺序依次进行二进制编码,共需要32个字节。

前8个字节的二进制编码是:0x01,0xf0,0x01,0xf0, 0xff,0xff,0xc0,0xf3,其余部分读者可以作为练习将其写出来。

修改为:大写字母O的二进制编码依次是:0x18,0x24,0x42, 0x42, 0x42, 0x42, 0x24, 0x18。

中国的“中”字的二进制编码按照从上到下,从左到右顺序依次进行二进制编码,共需要32个字节。

前8个字节的二进制编码的十六进制表示是:0x01,0x80,0x01,0x80, 0xff,0xff,0xc1,0x83,其余部分读者可以作为练习将其写出来。

2.ASCII码下数5行原文:从0x20到0x7f共95个编码修改为:从0x20到0x7e共95个编码2、p17原文:因此它的国标码是0x5050,而它的区位码是0x3030。

修改为:因此它的国标码是0x5056,而它的区位码是0x3036。

3、p25原文:1.9 求十进制数157和-153的8位、16位原码和8位、16位补码。

修改为:1.9 求十进制数157和-153的16位原码和16位补码。

4、p36例2.4后自然段的第3行原文:'t'、'\11'、'\011'、'\x9'和'\x09'均表示水平制表符。

修改为:'\t'、'\11'、'\011'、'\x9'和'\x09'均表示水平制表符。

5、p43 例2.9原文:!(year%4) && year%400 || !(year%400)上式等价于(!(year%4) && year%100 ) || !(year%400)修改为:!(year%4) && year%400 || !(year%400)上式等价于(!(year%4) && year%100 ) || !(year%4006、p76 例3.16原文:scanf(“%s%1s”, &c1, &c2);修改为:scanf(“%s%1s”, c1, &c2);7、p81例3.27原文:printf("%f/t", atof(” 123.456asdf”));printf("%f/t", atof(”\n-qwer”));printf("%f/t", atof(”\n+qwer”));printf("%f/n", atof(”3COM”));修改为:printf("%d\t", atoi(” 123.456asdf”));printf("%d\t", atoi(” 123456.789”));printf("%d\t", atoi(”\n-qwer”));printf("%d\t", atoi(”\n+qwer”));printf("%d\n", atoi(”3COM”));例3.28原文:printf("%d/t", atoi(” 123.456asdf”));printf("%d/t", atoi(” 123456.789”));printf("%d/t", atoi(”\n-qwer”));printf("%d/t", atoi(”\n+qwer”));printf("%d/n", atoi(”3COM”));修改为:printf("%d\t", atoi(” 123.456asdf”));printf("%d\t", atoi(” 123456.789”));printf("%d\t", atoi(”\n-qwer”));printf("%d\t", atoi(”\n+qwer”));printf("%d\n", atoi(”3COM”));p82 例3.28原文:printf("%ld/t", atol(” 123.456asdf”)); printf("%ld/t", atol(” 123456.789”));printf("%ld/t", atol(”\n-qwer”));printf("%ld/t", atol(”\n+qwer”));printf("%ld/n", atol(”3COM”));修改为:printf("%ld/t", atol(” 123.456asdf”)); printf("%ld\t", atol(” 123456.789”));printf("%ld\t", atol(”\n-qwer”));printf("%ld\t", atol(”\n+qwer”));printf("%ld\n", atol(”3COM”));8、p86 例3.33原文:printf(”input a character:\n”)c = getchar();c >= ’0’&& c <= ’9’? (d = ~(c –’0’) & 0xff, printf(”0x%x\n”, d)) : printf(”%c”, c);修改为:printf(”input a character:\n”);c = getchar();c >= ’0’&& c <= ’9’? (d = ~(c –’0’), printf(”0x%x\n”, d&0xff)) : printf(”%c ”, c);9、 p104 例4.15原文: Char c;修改为:char c;10、 p110 例4.22 修改为:计算 +-+-=!7!5!3)sin(753x x x x x ,11、 p112 倒数第6行原文: d=-(((3*x-4)*x)-5)*x+13/((9*x-8)*x-5)修改为:d=-( (((3*x-4)*x)-5)*x+13)/((9*x-8)*x-5) 12、 p113 第1行原文: d=-(((3*x-4)*x)-5)*x+13/((9*x-8)*x-5)修改为:d=-( (((3*x-4)*x)-5)*x+13)/((9*x-8)*x-5) 13、 p129原文:修改为:14、 p151 例5.11原文: if (n==0||==1) return 1;修改为:if (n==0||n ==1) return 1;15、 p166 第5.11题原文: (2) 若n i 是奇数,则n i+1=3n i +2修改为:(2) 若n i 是奇数,则n i+1=3n i +116、 p186 例7.1原文: initgraph( gdriver,gmode, "d:\\tc\\bgi");修改为:initgraph( &gdriver,&gmode, "d:\\tc\\bgi");17、 p194原文:修改为:18、 p222 倒数第8行开始原文: cout<<a[k]<<" ";<="" p="">cout<<endl;< p="">修改为:printf(“%d ”,a[k]);printf(“\n ”);原文:左边修改为:右边20、p292 第13行原文:while(*s++=*t++) ;修改为:while(*t++=*s++) ;21、p311 从9.11下数4行原文: B W Kernighan 和D M Ritchie修改为:B.W.Kernighan 和D.M.Ritchie22、p326 第10行原文:char num[4];修改为:char num[5];23、p330 倒数第1行原文:scanf("%d% d% %",&a.start.x,&a.start.y);修改为:scanf("%d% d%",&a.start.x,&a.start.y);24、p335 第16行原文:表达式的值是ˊaˊ,修改为:表达式的值是ˊmˊ,25、p367 倒数第3行原文:while(current->data!=n)修改为:while(current->data!=n && current != NULL) 26、p369 第2行原文:while(current->data!=n)修改为:while(current->data!=n && current != NULL) 27、p371 10.26原文:t=p1->next;prior2->next=p1;修改为:prior2->next=p1;t=p1->next;28、p402 倒数第6行原文:fwide函数修改为:fwi nd函数原文:fclose函数返回0,否则返回NULL。

C++ Primer Plus 勘误(第六版)

C++ Primer Plus 勘误(第六版)

删分号 加冒号 变小写 变小写 拼写错 加* 地址错 加d
所有权转让给 pu3 后就会被销毁。 变量错 -改_ 改小写 改小写 删掉 p 加叹号 加分号
W 为 0 表明, 默认的字段宽度为 0。 w 为 0 表明, 默认的字段宽度为 0。 改小写 拼写错 out 改为 in out 改为 in 改小写
P511 / F5 P536 / 图 14.1 / B5 P536 / B2 P536 / B1 P622 / F8 P667 / 16.2 / F7 P668 / 图 16.2-demo2-#2 / B2 P669 / 16.2.1 / B2 P673 / 16.2.3 / F14 P692 / 16.4.4-2 / F3 P708 / F10 P708 / F12 P721 / B7 P738 / 图 17.4-最 下面的图 P741 / 17.2.3 / B2 P744 / B1 P762 / B12 P755 / 表 17.8 / F5 P755 / 表 17.8 / F6 P782 / B9
Fn:正数第 n 行,Bn:倒数第 n 行
4
修改为 程序清单 2.2 carrots.cpp int、unsigned int、long、… unsigned int 转义序列\n 表示换行符 8.33E-4 表示 8.33/10 9.11e-31 kg 表示… d.dddE-n 指的是… perks 类型的变量—perks mr_blug; 程序需要 strlen(temp)+1 个字符 则 strcmp()将返回一个正数值 声明为 unsigned int 类型 rodents address = 0x0065fd44 我 们 使 用 “ coordin.h ” 而 不 是 , <coordin.h>。 Embarcadero C++ Builder 从而跳到#endif 后面的一行上 int *pin = new int {6}; cout << bozetta.Retort(); #define STOCK10_H_ Bozo fufu{“Fufu”, “O’Dweeb”}; // C++11 编译器将用 12 来替换它 随便说一句,程序清单 12.1… Klunk() { klunk_ct = 0; } 则 operator<()函数返回 true。 使用标准的 strcmp()函数 delete [] c_pointer; Show (&player1); Show (&rplayer1); void Move(int nx, int ny) { x = nx; y = ny; } void Move(int nx, int ny) { x = nx; y = ny; } void Move(int nx, int ny) { x = nx; y = ny; } 派生出 Ellipse 类和 Circle 类

《案例式C语言实验与习题指导》勘误表

《案例式C语言实验与习题指导》勘误表

8.编程题。输入 5 个字符串,输出其中最长的字符串。
P43
第 19 行
int main()
P46 倒数第 15 行 5.编程题。通讯录排序。建立
void main() 5.编程题。建立
P46 倒数第 13 行 编写一个函数计算某日是该年中的第几天
编写一个函数计算某日期是该年中的第几天
P46
倒数第 9 行 8.编程题。时间换算。用结构体类型
大公约数和最小公倍数。
数。
P37
倒数第 9 行
for(i=0;i<3;i++) for(j=0;j<3;j++)
for(i=0;i<n;i++) for(j=0;j<n;j++)
P38
倒数第 3 行
6.编程题。设计一个函数 process( ),在主函数调用它的时 候,每次实现不同功能。输入 a,b 两个数,调用函数 process( )4 次,分别求 a,b 的和、差、积、商。函数 process 每次计算 的结果要求返回主函数中输出。
3
P54
倒数第 5 行 4.编程题。计算器。设计
【实验结果与分析】
4.编程题。设计
P54
倒数第 3 行 从实验内容中选 1~2 题,将源程序、运行结果和分析及实 将整个内容删除。
验中遇到的问题和解决方法写在实验报告中。
P57
第 14 行
5.若有变量说明语句 char m='\63' ,
P57
第 22 行
5.printf 函数中用到格式%5s,
P63
第 11 行
当执行第一个输入语句时,从键盘输入:12.3,

【百度资料】c++_primer_plus第六版学习笔记201501112210+

【百度资料】c++_primer_plus第六版学习笔记201501112210+

【百度资料】c++_primer_plus第六版学习笔记201501112210+笔记⽬录第⼀章:预备知识41、c++简介 (4)2、程序创建技巧 (4)3、源⽂件扩展名 (4)第⼆章:开始学习c++ (5)1、c++代码区分⼤⼩写。

(5)2、c++代码结构 (5)3、函数 (5)4、注译 (5)5、c++预处理器和iostream⽂件 (5)6、头⽂件名 (6)7、名称空间 (6)8、cout进⾏c++输出 (6)9、控制符endl (6)10、c++代码格式 (6)C++语句 (6)1、声明语句和变量 (6)2、赋值语句 (7)3、cout的新⽤法 (7)4、使⽤cin (7)5、使⽤cout拼接 (7)6、类简介 (7)7、函数 (7)8、函数原型 (8)9、使⽤库函数 (9)10、函数变体 (9)12、函数格式 (10)13、函数头 (10)14、复习int main()函数头 (10)总结 (12)复习题 (12)编程练习 (13)第三章、处理数据 (15)1、简单变量 (15)2、变量名 (15)3、整型 (15)4、整型short、int、long和long long (15)※注译:位与字节 (16)要了解的概念: (16)5、运算符sizeof和头⽂件limits (17)符号常量-预处理器⽅式(注译) (18)6、初始化 (18)c++初始化⽅式 (18)7、⽆符号类型 (19)8、选择整数类型 (20)9、整型字⾯值 (20)10、C++如何确定常量的类型 (21)11、char类型:字符和⼩整数 (22)成员函数cout.put() (23)Char字⾯值and转义序列 (23)通⽤字符名 (24)signed char和unsigned char (24)wcha_t (25)C++11新增的类型:char16_t和char32_t (25) Bool类型 (25)12、const限定符(定义符号常量) (26)13、浮点数 (26)书写浮点数 (26)浮点类型 (27)浮点常量 (28)运算符优先级和结合性 (29)除法分⽀ (29)运算符重载(注译) (29)求模运算符 (30)类型转换 (30)14、总结 (33)15、第三章复习题 (33)16、编程练习 (34)第四章、复合类型 (34)1、数组 (34)3、数组的初始化规则 (36)4、c++数组初始化⽅法 (36)5、字符串 (36)拼接字符串常量 (37)在数组中使⽤字符串 (37)字符串输⼊ (38)每次读取⼀⾏字符串输⼊ (39)混合输⼊字符串和数字 (40)6、string类简介 (41)C++11字符串初始化 (41)赋值、拼接和附加 (42)String类的其他操作(包含了确定字符数函数) (42)String类I/O (43)其他形式的字符串⾯值 (44)7、结构简介 (44)在程序中使⽤结构 (45)C++结构初始化 (47)结构可以将string类作为成员吗 (47)其他结构属性 (48)结构数组 (48)结构中的位字段 (48)枚举的取值范围 (50)11、指针和⾃由存储空间 (51)声明和初始化指针 (52)指针的危险 (53)指针和数字 (54)使⽤new来分配内存 (54)使⽤delete释放内存 (55)使⽤new来创建动态数组 (56)12、指针、数组和指针算术 (58)指针⼩结 (60)指针和字符串 (62)使⽤new创建动态结构 (64)第⼀章:预备知识1、c++简介c⾯向过程,c++⾯向对象。

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

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

第二章:开始学习C++ n”;}<<endl; return 0;}double C2F(double t){return *t+32;}<<endl; return 0;}double convert(double t){return 63240*t;n"; return 0;}style(miles per gallon):"<<endl; cout<<Euro_style<<"L/100Km = "<<*Euro_style<<" mpg\n"; return 0;}Enter the automobile gasoline consumption figure inEuropean style(liters per 100 kilometers):Converts to . style(miles per gallon):L/100Km = mpgPress any key to continuestyle(miles per gallon):";double US_style;cin>>US_style;cout<<"Converts to European style(miles per gallon):"<<endl;cout<<US_style<<" mpg = "<< *US_style<<"L/100Km\n"; return 0;}style(miles per gallon):19Converts to European style(miles pergallon): 19 mpg = 100KmPress any key to continue第四章复合类型n";return 0;}rand<<endl<<snack[i].weight<<endl<<snack[i].calory<<endl<<endl;}return 0;}rand="A";eight=;snack[0].calory=200;snack[1].brand="B";snack[1].weight=;snack[1].calory=400;snack[2].brand="C";snack[2].weight=;snack[2].calory=500;for(int i=0;i<3;i++){cout << " brand: " << snack[i].brand<< endl; cout << " weight: " <<snack[i].weight << endl;cout << " calorie: " << snack[i].calory << endl<<endl;}delete [] snack;return 0;}et(); car* ps=newcar[num];for(int i=0;i<num;++i){cout<<"Car #"<<i+1<<":\n";cout<<"Please enter the make: ";getline(cin,ps[i].name); c out<<"Pleaseenter the year made: ";(cin>>ps[i].year).get();}cout<<"Here is your collection:\n";for(int i=0;i<num;++i)cout<<ps[i].year<<" "<<ps[i].name<<endl;delete [] ps;return 0;}#include <iostream>#include <string> usingnamespace std; structcar{string maker; intyear;};int main(){int number;cout << "How many cars do you wish to catalog "; cin >>number;car* a = new car[number];for (int i = 0; i < number; i++){cout << "Car #" << i+1 << ": " << endl; cout <<"Please enter the maker: "; ();getline(cin,a[i].maker);cout << "Please enter the year made: "; cin >>a[i].year;}cout << "Here is your collection: " << endl; for (inti = 0; i < number; i++)cout << a[i].year << " " << a[i].maker <<endl; delete [] a;return 0;}#include <iostream> usingnamespace std; struct car{char maker[20];int year;};int main(){int number;cout << "How many cars do you wish to catalog "; cin >>number;car* a = new car[number];for (int i = 0; i < number; i++){cout << "Car #" << i+1 << ": " << endl; cout <<"Please enter the maker: "; ();(a[i].maker, 20);cout << "Please enter the year made: "; cin >>a[i].year;}cout << "Here is your collection: " << endl; for (int i = 0; i < number; i++)cout << a[i].year << " " << a[i].maker <<endl; delete [] a;return 0;}n"; return 0;}n";return 0;}和的区别是:word != "done",因为当 word = done 一样时,返回值为1,不一样时才是返回0.;for(int k=0;k<=i;++k)cout<<"*";cout<<endl;}return 0;}第六章分支语句和逻辑运算符n"; break;case 'p':cout<<"A maple is a pianist.\n";break;case 't':cout<<"A maple is a tree.\n";break;case 'g':cout<<"A maple is a game.\n";}return 0;}#include <iostream> usingnamespace std; void show();int main(){show();char choice;while (cin >> choice){switch(choice){case 'c' : cout << "It's a carnivore.\n"; break;case 'p' : cout << "It's a pianist.\n"; break;case 't' : cout << "A maple is a tree.\n"; break;case 'g' : cout << "It's a game.\n"; break;default : cout << "Please enter a c, p, t, or g:";}}return 0;}void show(){cout << "Please enter one of the following choices: \n" "c) carnivore p) pianist\n""t) tree g) game\n";}display by name b. display by title\n"<<"c. display by bopname d. diplay by preference\n"<<"q. quit\n";char ch;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}};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; e lseif(member[i].preference==2)cout<<member[i].bopname<<endl;}break;}cout<<"Next choice: ";}cout<<"Bye!\n";return 0;}#include <iostream> usingnamespace std; const intstrsize = 30; struct bop{char fullname[strsize];char title[strsize]; charbopname[strsize]; intpreference;};void show(); intmain(){bop A[5] ={{"Wimp Macho", "Teacher", "HAHA", 0},{"Raki Rhodes", "Junior Programmer", "LIAR", 1},{"Celia", "engineer", "MIPS", 2},{"Hoppy Hipman", "Analyst Trainee", "WAHU", 1},{"Pat Hand", "Student", "LOOPY", 2}};cout << "Benevolent Order of Programmers Report\n"; show();cout << "Enter your choice: "; charchoice;cin >> choice;while (choice != 'q'){switch(choice){case 'a' : cout << A[0].fullname << endl << A[1].fullname << endl<< A[2].fullname << endl << A[3].fullname << endl<< A[4].fullname << endl; break;case 'b' : cout << A[0].title << endl << A[1].title << endl<< A[2].title << endl << A[3].title << endl<< A[4].title << endl;break;case 'c' : cout << A[0].bopname << endl << A[1].bopname << endl<< A[2].bopname << endl << A[3].bopname << endl<< A[4].bopname << endl; break;case 'd' : cout << A[0].fullname << endl << A[1].title << endl<< A[2].bopname << endl << A[3].title << endl<< A[4].bopname << endl;break;default : cout << "That's not the proper choice.\n";}cout << "Next choice: ";cin >> choice;}cout << "Bye!\n";return 0;}void show(){cout << "a. display by name b. display by title\n"<< "c. display by bopname d. display by preference\n"<< "q. quit\n";}ame); c out<<"请输入第"<<i+1<<"位捐款人捐款的数目:"; cin>>ps[i].money;();}cout<<"Grand Patrons:\n";for(int i=0;i<num;++i)if(ps[i].money>10000){cout<<ps[i].name<<"\n"<<ps[i].money<<endl;++temp;}if(temp==0)cout<<"none\n";cout<<"Patrons:\n";for(int i=0;i<num;++i)if(ps[i].money<=10000){cout<<ps[i].name<<"\n"<<ps[i].money<<endl;++temp;}if(temp==0)cout<<"none\n";delete [] ps;return 0;}#include <iostream>#include <string> usingnamespace std; structcharity{string name;double money;};int main(){int number; intcount = 0;cout << "Please enter the number of donator: "; cin >>number;charity *pt = new charity[number]; for(int i = 0; i < number; i++){cout << "Please enter your name: "; ();getline(cin, pt[i].name);cout << "Please enter the money you are going to donate: "; cin >>pt[i].money;if(pt[i].money > 10000)count++;}if(count == 0)cout << "None(money > 10000)"; else{cout << "Grand Patron\n"; for(int i =0; i < number; i++){if(pt[i].money > 10000)cout << pt[i].name << " " << pt[i].money << endl;}}cout << endl;if(10 - count == 0)cout << "None(money < 10000)"; else {cout << "Patron\n";for(int i = 0; i < number; i++){if(pt[i].money < 10000)cout << pt[i].name << " " << pt[i].money << endl;}}return 0;}n"; exit(EXIT_FAILURE);}inFile>>ch; while()){++sum;inFile>>ch;}if())cout<<"End of file reached.\n";else if())cout<<"Input terminated by data mismatch.\n";elsecout<<"Input terminated for unkonwn reason.\n";cout<<"总共有"<<sum<<"个字符在这个文件中。

C++PrimerPlus第六版课后题第六章

C++PrimerPlus第六版课后题第六章

1.#include<iostream>#include<cctype>int main(){usingnamespace std;char ch;cin.get(ch);while (ch != '@'){if (islower(ch))cout<<char (toupper(ch));if (isupper(ch))cout<<char (tolower(ch));if (isdigit(ch))cout<<" ";cin.get(ch);}cout<<ch ;return 0;}2.#include<iostream>constint Number = 10;int main(){usingnamespace std;double number[Number];cout<<"Please enter "<< Number <<" numbers ."<<endl;int i = 0;cout<<"donation #1 : ";while (i< Number &&cin>> number[i]){if (++i< Number)cout<<"donation #"<< i+1 <<" : " ;}double total = 0.0;double average;for (int j = 0; j <i; j++)total += number[j];average = total / i;int count = 0;for (int j = 0; j <i; j++){if( number[j] > average)count ++;}cout<<"The average is "<< average <<" . "<<endl;cout<<"the number over average is : "<< count <<endl;return 0;}3.#include<iostream>void showmenu();void tree();usingnamespace std;int main(){showmenu();char choice;cout<<"Please enter a c, p, t, or g : ";cin>> choice;if (choice != 'c'&& choice != 'p'&& choice != 't'&& choice != 'g'){cout<<"Please enter a c, p, t, or g : ";cin>> choice;}while (choice == 'c' || choice == 'p' || choice == 't' || choice == 'g' ) {switch (choice){case'c' : cout<<" It carnivore."<<endl;break;case'p' : cout<<"He is a pianist. "<<endl;break;case't' : tree();break;case'g' : cout<<"It's a game."<<endl;break;default : cout<<"That's not a choice."<<endl;}cin>> choice;}return 0;}void showmenu(){cout<<"Please enter one of the following choices: "<<endl;cout<<"c) carnivore p) pianist"<<endl;cout<<"t) tree g) game"<<endl;cout<<"f "<<endl;}void tree(){cout<<"A maple is a tree."<<endl;}4.#include<iostream>usingnamespace std;constint strsize = 80;//BOP name strucurestruct bop{char fullname[strsize];char title[strsize];char bopname[strsize];int preference;};void showmenu();void fullname();void preference();int main(){bop a1[5]={{"Wimp Macho", "title_1", "bopname_1", 0},{"Raik Rhodes", "title_2", "bopname_2", 1},{"Celia La", "title_3", "bopname_3", 1},{"Hoppy Hip", "title_4", "bopname_4", 1},{"Pat Hand", "title_5", "bopname_5", 1}};cout<<"Benevolent Order of Programmers Report"<<endl;showmenu();char choice;cout<<"Enter your choice : ";cin>> choice;while (choice >= 'a'&& choice <= 'd' ){switch (choice){case'a' : fullname();break;case'b' : cout<< a1[0].title <<"\n"<< a1[1].title <<"\n"<< a1[2].title <<"\n"<< a1[3].title <<"\n"<< a1[4].title <<endl;break;case'c' : cout<< a1[0].bopname<<"\n"<< a1[1].bopname<<"\n"<< a1[2].bopname<<"\n"<< a1[3].bopname<<"\n"<< a1[4].bopname<<endl;break;case'd' : preference();break;}cout<<"Next choice : ";cin>> choice;}cout<<"Bye!"<<endl;return 0;}void showmenu(){cout<<"a. display by name b. display by title"<<endl;cout<<"c. display by bopname d. display by prerence"<<endl;cout<<"q.quit "<<endl;}void fullname(){bop a1[5]={{"Wimp Macho", "title_1", "bopname_1", 0},{"Raik Rhodes", "title_2", "bopname_2", 1},{"Celia La", "title_3", "bopname_3", 1},{"Hoppy Hip", "title_4", "bopname_4", 1},{"Pat Hand", "title_5", "bopname_5", 1}};cout<< a1[0].fullname<<"\n"<< a1[1].fullname<<"\n"<< a1[2].fullname<<"\n"<< a1[3].fullname<<"\n"<< a1[4].fullname<<endl;}void preference(){bop a1[5]={{"Wimp Macho", "title_1", "bopname_1", 0},{"Raik Rhodes", "title_2", "bopname_2", 1},{"Celia La", "title_3", "bopname_3", 1},{"Hoppy Hip", "title_4", "bopname_4", 1},{"Pat Hand", "title_5", "bopname_5", 1} };for (int i = 0; i< 5; i++){if (a1[i].preference == 0)cout<< a1[i].fullname<<endl;elseif (a1[i].preference == 1)cout<< a1[i].title <<endl;elseif (a1[i].preference == 2)cout<< a1[i].bopname<<endl;}}5.#include<iostream>usingnamespace std;int main(){int tvarps;double tax = 0;cout<<"Enter your income : " ;while (cin>>tvarps&&tvarps> 0){if (tvarps<= 5000)tax = 0.00;elseif (tvarps> 5000 &&tvarps<= 15000)tax = 5000 * 0.00+ 10000 * 0.10 ;elseif (tvarps> 5000 &&tvarps<= 35000)tax = 5000 * 0.00+ 10000 * 0.10 + 20000 * 0.15 ;elseif (tvarps> 35000)tax = 5000 * 0.00+ 10000 * 0.10 + 20000 * 0.15 + 3000 * 0.2;cout<<"Yout tax is "<< tax <<endl;}return 0;}6.#include<iostream>#include<string>usingnamespace std;struct blank{string name;int money;};int main(){int number;cout<<"Please enter the number of devoters : ";cin>> number;blank * ps = new blank[number];for (int i = 0; i< number; i++){cout<<"Please enter the name of devoters : ";cin.sync();getline(cin, ps[i].name);cout<<"Please enter the price of devoters : ";cin>>ps[i].money;}int temp = 0;cout<<"The following persons are Grand Patrons. "<<endl;for (int i = 0; i< number; i++){if (ps[i].money > 10000){cout<<ps[i].name <<" "<<ps[i].money <<endl;temp++;}}if (temp == 0)cout<<"none"<<endl;cout<<"The following persons are Patrons. "<<endl;int num = 0;for (int i = 0; i< number; i++){if (ps[i].money < 10000){cout<<ps[i].name <<" "<<ps[i].money <<endl;num++;}}if (num == 0)cout<<"none"<<endl;return 0;}7.Switch 形式:#include<iostream>#include<string>#include<cctype>usingnamespace std;int main(){string word;int yuanyin = 0;int fuyin = 0;int others = 0;cout<<"Enter words (q to quit): "<<endl;cin>> word;while (word != "q"&& word != "Q"){if (isalpha(word[0])){switch(word[0]){case'a': yuanyin++;break;case'e': yuanyin++;break;case'i': yuanyin++;break;case'o': yuanyin++;break;case'u': yuanyin++;break;default:fuyin++;break;}}elseothers++;cin>> word;}cout<<yuanyin<<" words beginning with vowels "<<endl;cout<<fuyin<<" words beginning with consonants "<<endl;cout<< others <<" others "<<endl;return 0;}If形式:#include<iostream>#include<string>#include<cctype>usingnamespace std;int main(){string word;int yuanyin = 0;int fuyin = 0;int others = 0;cout<<"Enter words (q to quit): "<<endl;cin>> word;while (word != "q"&& word != "Q"){if (isalpha(word[0])){if (word[0] == 'a' || word[0] == 'e' || word[0] == 'i' || word[0] == 'o' || word[0] == 'u')yuanyin++;elsefuyin++;}elseothers++;cin>> word;}cout<<yuanyin<<" words beginning with vowels "<<endl;cout<<fuyin<<" words beginning with consonants "<<endl;cout<< others <<" others "<<endl;return 0;}8.。

《C++_Primer_Plus(第6版)中文版》编程练习6-10章

《C++_Primer_Plus(第6版)中文版》编程练习6-10章

else if (member[i].preference == 1) cout << member[i].title << endl; else cout << 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); else tax = RATE1 * (LEV2 - LEV1) + RATE2 * (LEV3 - LEV2) + RATE3 * (income - LEV3); cout << "You owe Neutronia " << tax << " tvarps in taxes.\n"; return 0; }

C-Primer-Plus第六版中文版习题答案

C-Primer-Plus第六版中文版习题答案

C Primer Plus第六版中文版习题答案Github: /zhayujie/C-Primer-Plus第一章1.#include <stdio.h>int main(void) {double inch, cm;printf("Please input the inches: ");scanf("%lf", &inch);cm = inch * 2.54;printf("%g cm\n", cm);return 0;}第二章3.#include<stdio.h>int main(void){int days,years=21;days=years*365;printf("我的年龄是%d岁,%d天\n",years,days);return 0;}4.#include<stdio.h>void jolly(void);void deny(void);int main(void){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");}5.#include<stdio.h>void br(void);void ic(void);int main(void){br();printf(",");ic();printf("\n");ic();printf("\n");br();printf("\n");return 0;}void br(void){printf("Brazil,Russia");}void ic(void){printf("India,China");}6.#include<stdio.h>int main(void){int toes=10;int toes_2,toes2;toes_2=2*toes;toes2=toes*toes;printf("toes是%d,toes的两倍是%d,toes的平方是%d\n",toes,toes_2,toes2); return 0;}8.#include<stdio.h>void one_three(void);void two(void);int main(void){printf("starting now\n");one_three();}void one_three(void){printf("one\n");two();printf("three\n");printf("done!\n");}void two(void){printf("two\n");}第三章2.#include<stdio.h>int main(void){char ch;printf("please input a number:");scanf("%d",&ch);printf("%c\n",ch);return 0;}4.#include<stdio.h>int main(void){float a;printf("Enter a floating-point value: ");scanf("%f",&a);printf("fixed-point notation: %f\n",a);printf("exponential notation: %e\n",a);return 0;}5.#include<stdio.h>int main(void){int age;double seconds;printf("please input your age: ");scanf("%d",&age);seconds=age*3.156e7;printf("the corresponding seconds are: %e\n",seconds);return 0;}7.#include<stdio.h>int main(void){float inches,cms;printf("input your height(inch): ");scanf("%f",&inches);cms=inches*2.54;printf("your height(cm): %f\n",cms);return 0;}8.#include<stdio.h>int main(void){float pint,ounce,soupspoon,teaspoon,cup;printf("input the number of cups: ");scanf("%f",&cup);pint=cup/2;ounce=cup*8;soupspoon=ounce*2;teaspoon=soupspoon*3;printf("they are equivalent of:\n%f pint\n%f ounce\n%f soupspoons\n%f teaspoons\n",pint,ounce,soupspoon,teaspoon);return 0;}第四章1.#include<stdio.h>int main(void){char firstname[40],lastname[40];printf("Input your firstname: ");scanf("%s",firstname);printf("Input your lastname: ");scanf("%s",lastname);printf("Your name is %s,%s\n",firstname,lastname);return 0;}2.#include<stdio.h>#include<string.h>int main(void){char name[40];int width;printf("Input your name: ");scanf("%s",name);width=strlen(name)+3;printf("%*s\n",width,name); //输入的名和姓中间不能分隔return 0;}4.#include<stdio.h>int main(void){float height;char name[40];printf("Input your height(cm) and name: ");scanf("%f%s",&height,name);height=height/100;printf("%s, you are %.3fm tall\n",name,height);return 0;}5.#include<stdio.h>int main(void){float speed,size,time;printf("Input the download speed(Mb/s) and the file size(MB):\n"); scanf("%f%f",&speed,&size);time=size/speed*8.0;printf("At %.2f megabits per second, a file of %.2f megabytes\n",speed,size);printf("downloads in %.2f seconds.\n",time);return 0;}6.#include<stdio.h>#include<string.h>int main(void){char firstname[40],lastname[40];printf("Input your firstname: ");scanf("%s",firstname);printf("Input your lastname: ");scanf("%s",lastname);printf("%s %s\n",firstname,lastname);printf("%*d %*d\n",strlen(firstname),strlen(firstname),strlen(lastname),strlen(lastname)); printf("%s %s\n",firstname,lastname);printf("%*d %*d\n",-strlen(firstname),strlen(firstname),-strlen(lastname),strlen(lastname) );return 0;}7.#include<stdio.h>#include<float.h>int main(void){double a=1.0/3.0;float b=1.0/3.0;printf("%.6f %.6f\n",a,b); //左侧double型右侧float型printf("%.12f, %.12f\n",a,b);printf("%.16f, %.16f\n",a,b);printf("DBL_DIG: %d\n",DBL_DIG);printf("FLT_DIG: %d\n",FLT_DIG);return 0;}8.#include<stdio.h>#define GALLON 3.758 //1 gallon=3.785 liters#define MILE 1.609 //1 mile=1.609 kilometersint main(void){float gallon,mile;printf("Input miles and gallons: ");scanf("%f%f",&mile,&gallon);printf("Miles per gallon: %.1f\n",mile/gallon);printf("Litre per 100 kilometers: %.1f\n",gallon*GALLON/(mile*MILE)*100);return 0;}第五章1.#include<stdio.h>#define H_P_M 60 //1h=60minint main(void){int hour,min,left;printf("Enter the number of minutes: ");scanf("%d",&min);while(min>0){hour=min/H_P_M;left=min%H_P_M;printf("%d minutes is %d hours and %d minutes.\n",min,hour,left); printf("Enter your next value: ");scanf("%d",&min);}printf("Good bye!\n");return 0;}2.#include<stdio.h>int main(void){int num,count;printf("Input a integer: ");scanf("%d",&num);count=0;while(count++<11){printf("%d ",num);num++;}printf("\n");return 0;}3.#include<stdio.h>#define DAYS_PER_WEEK 7 //一周7天int main(void){int day,week,left;printf("Input the number of days: ");scanf("%d",&day);while(day>0){week=day/DAYS_PER_WEEK;left=day%DAYS_PER_WEEK;printf("%d days are %d weeks, %d days.\n",day,week,left); printf("Next input: ");scanf("%d",&day);}return 0;}4.#include<stdio.h>#define CM_PER_FEET 30.48 //1feet=30.48cm#define CM_PER_INCH 2.54 //1inch=2.54cmint main(void){int feet;float cm,inch;printf("Enter a height in centimeters: ");scanf("%f",&cm);while(cm>0){feet=(int)(cm/CM_PER_FEET);inch=(cm-feet*CM_PER_FEET)/CM_PER_INCH;printf("%.1f cm = %d feet, %.1f inches\n",cm,feet,inch); printf("Enter a height in centimeters (<=0 to quit): "); scanf("%f",&cm);}printf("bye\n");return 0;}5.#include<stdio.h>int main(void){int count,sum,days;printf("Input the number of days: ");scanf("%d",&days);count=sum=0;while(count++<days)sum=sum+count;printf("The money you earned: %d\n",sum);return 0;}6.#include<stdio.h>int main(void){int count,sum,days;printf("Input the number of days: ");scanf("%d",&days);count=sum=0;while(count++<days)sum=sum+count*count;printf("The money you earned: %d\n",sum);return 0;}7.#include<stdio.h>void cube(double n);int main(void){double num;printf("Input a number: ");scanf("%lf",&num);cube(num);}void cube(double n){printf("The cube of %f is %f\n",n,n*n*n);}8.#include<stdio.h>int main(void){int num1,num2;printf("This program computes moduli.\n");printf("Enter an integer to serve as the second operand: ");scanf("%d",&num1);printf("Now enter the first operand: ");scanf("%d",&num2);while(num2>0){printf("%d %% %d is %d\n",num2,num1,num2%num1);printf("Enter next number for first operand (<= 0 to quit): "); scanf("%d",&num2);}printf("Done\n");}9.#include<stdio.h>void Temperatures(double fah);int main(void){double fah,cel,kel;//华氏温度,摄氏温度,开氏温度printf("Input the Fahrenheit temperature: ");while(scanf("%lf",&fah)==1){Temperatures(fah);printf("Next input: ");}printf("Done.\n");}void Temperatures(double fah){const double a=5.0,b=9.0,c=32.0,d=276.13; printf("%.2f ℉ is %.2f ℃, %.2f K.\n",fah,a/b*(fah-c),a/b*(fah-c)+d);}第六章1.#include<stdio.h>#define SIZE 26int main(void){char ch[SIZE];int index;for(index=0;index<SIZE;index++){ch[index]='a'+index;printf("%c ",ch[index]);}printf("\n");return 0;}2.#include<stdio.h>int main(void){int i,j;for(i=1;i<=5;i++){for(j=1;j<=i;j++)printf("$");printf("\n");}return 0;}3.#include<stdio.h>int main(void){int i,j;for(i=1;i<=6;i++){for(j=0;j<i;j++)printf("%c",'F'-j); printf("\n");}return 0;}4.#include<stdio.h>#define ROWS 6int main(void){char ch;int i,j;for(ch='A',i=0;i<ROWS;i++) {for(j=0;j<=i;j++)printf("%c",ch++); printf("\n");}return 0;}5.#include<stdio.h>#define ROWS 5int main(void){char ch='A';int i,j;for(i=1;i<=ROWS;i++){for(j=1;j<=ROWS-i;j++)printf(" ");for(j=0;j<i;j++)printf("%c",ch+j);for(j=i-2;j>=0;j--)printf("%c",ch+j);printf("\n");}return 0;}6.#include<stdio.h>int main(void){int max,min,num;printf("Input the min and max: ");scanf("%d%d",&min,&max);printf("%10s%10s%10s\n","number","square","cube");for(num=min;num<=max;num++)printf("%10d%10d%10d\n",num,num*num,num*num*num); return 0;}7.//与题目不同打印的是句子#include<stdio.h>#include<string.h>#define SIZE 40int main(void){int i,index=-1;char ch[SIZE];printf("Input a word: ");do{ index++;scanf("%c",&ch[index]);}while(ch[index]!='\n');for(i=index+1;i<=40;i++)ch[i]='\0';for(index=strlen(ch);index>=0;index--)printf("%c",ch[index]);printf("\n");return 0;}8.#include<stdio.h>int main(void){double n1,n2;printf("Input two numbers: ");while(2==scanf("%lf%lf",&n1,&n2)){printf("%f\n",(n1-n2)/n1*n2);printf("Input your next pair of numbers: ");}printf("Bye!\n");return 0;}9.#include<stdio.h>double calculate(double n1, double n2);int main(void){double num1, num2;printf("Input two numbers: ");while (2 == scanf("%lf%lf", &num1, &num2)) //输入两个浮点数 {printf("%f\n", calculate(num1, num2)); //函数调用printf("Input your next pair of numbers: ");}printf("Bye!\n");return 0;}double calculate(double n1, double n2){return ((n1 - n2) / (n1 * n2)); //返回运算结果}10.#include <stdio.h>int main(void){int lower, upper;int num, sum;printf("Enter lower and upper integer limits: ");scanf("%d%d", &lower, &upper);while (lower < upper){for (sum=0, num=lower; num <= upper; num++)sum = sum + num * num; //计算平方和printf("The sums of the squares from %d to %d is %d\n", lower * lower, upper * upper, sum); //输出结果printf("Enter next set of limits: ");scanf("%d%d", &lower, &upper); //下一次输入}printf("Done\n");return 0;}11.#include <stdio.h>#define SIZE 8int main(void){int num[SIZE];int index;printf("Enter 8 integers: ");for (index=0; index<SIZE; index++) //输入8个整数scanf("%d", &num[index]);for (index=SIZE-1; index >= 0; index--) //倒序输出printf("%d ", num[index]);printf("\n");return 0;}12.#include <stdio.h>int main(void){double sum1=0, sum2=0;int count, items, sign;printf("Enter the items: ");scanf("%d", &items); //输入序列的项数for (count=1, sign=1; count <= items; count++, sign *= -1){sum1 += 1.0 / count;sum2 += 1.0 * sign / count;} //分别计算两序列的和 printf("1.0 + 1.0/2.0 + 1.0/3.0 + 1.0/4.0 + ... = %f\n", sum1); printf("1.0 - 1.0/2.0 + 1.0/3.0 - 1.0/4.0 + ... = %f\n", sum2);return 0;}13.#include <stdio.h>#define SIZE 8int main(void){int index, count, num[SIZE];for (index = 0, count = 1; index < SIZE; index++){count *= 2;num[index] = count;} //for循环将数组元素设为2的前8次幂 index=0; //初始化index的值doprintf("%d ", num[index++]);while (index < SIZE); //do while循环显示数组元素的值printf("\n");return 0;}14.#include <stdio.h>#define SIZE 8int main(){double num1[SIZE], num2[SIZE];int index1, index2, index;printf("Enter 8 numbers to the first array:\n");for (index1 = 0; index1 < SIZE; index1++)scanf("%lf", &num1[index1]); //向第一个数组输入8个数 num2[0] = num1[0];for (index1 = 1, index2 = 1; index1 < SIZE; index1++, index2++) num2[index2] = num2[index2-1] + num1[index1];//为第二个数组赋值(是第一个数组对应的元素之和)printf("The first array: ");for (index=0; index < SIZE; index++) {printf("%6.2f", num1[index]);} //输出第一个数组的内容 printf("\nThe second array: ");for (index=0; index < SIZE; index++) {printf("%6.2f", num2[index]); //输出第二个数组的内容 }printf("\n");return 0;}15.#include <stdio.h>#include <string.h>#define SIZE 255int main(void){int index;char ch[SIZE];printf("Enter a line: ");for(index = 0, scanf("%c", &ch[0]); ch[index] != '\n';){index++;scanf("%c", &ch[index]);} //输入内容到字符数组中,回车时结束for(index += 1; index < SIZE; index++)ch[index] = '\0'; //将数组剩余空间补充为'\0'for(index = strlen(ch); index >=0; index--)printf("%c", ch[index]); //倒序输出内容printf("\n");return 0;}16.#include <stdio.h>#define RATE_DAPHNE 0.1#define RATE_DEIRDRE 0.05 //两人的利率#define MONEY 100int main(void){int year;double daphne = MONEY, deirdre = MONEY; //两人的初始投资额相同for (year = 1; daphne >= deirdre; year++){daphne += MONEY * RATE_DAPHNE;deirdre += deirdre * RATE_DEIRDRE;}//计算Deirdre投资额超过Daphne需要的年数和当时的金额printf("After %d year, Deirdre's investment will be more than Daphne's,\n""Daphne's investment will be $%lf,\nand Deirdre's investment will be $%lf.\n",year, daphne, deirdre); //输出结果return 0;}17.#include <stdio.h>#define INITIAL_MONEY 100 //账户初始金额为100万元#define ANNUAL_RATE 0.08 //年利率为8%int main(void){int year;double money;for(year = 1, money=INITIAL_MONEY; money>0; year++)money += money * ANNUAL_RATE - 10; //计算每年年终的账户余额printf("After %d years, Chuckie will draw all money from his account.\n", year);return 0;}18.#include <stdio.h>#define INITIAL_NUMBER 5 //初始朋友数为5人#define DUNBAR_NUMBER 150 //邓巴数int main(void){int week;int number = INITIAL_NUMBER;for (week = 1; number <= DUNBAR_NUMBER; week++){number = (number - week) * 2; //计算每周的朋友数量printf("After %d week, the number of Rabnud's friends is %d\n", week, number);}return 0;}第七章1.#include <stdio.h>int main(void){char ch;int n_space = 0; //空格数int n_newline = 0; //换行数int n_others = 0; //其他字符数printf("Enter some text; Enter # to quit.\n"); while ((ch = getchar()) != '#'){if (ch == ' ')n_space++;else if (ch == '\n')n_newline++;elsen_others++;}printf("Spaces: %d, newlines: %d, others: %d\n", n_space, n_newline, n_others);return 0;}2.#include <stdio.h>#define CHARS_PER_LINE 8 //每行字符数int main(void){char ch;int n_chars = 1; //字符数printf("Enter some characters(# to quit):\n"); while ((ch = getchar()) != '#'){printf("%3c(%3d) ", ch, ch);if (n_chars++ % CHARS_PER_LINE == 0)printf("\n");}printf("\n");return 0;}3.#include <stdio.h>int main(void){int num;int n_even = 0, n_odd = 0; //偶数和奇数个数int sum_even = 0, sum_odd = 0; //偶数和奇数和printf("Enter some integers(0 to quit):\n");scanf("%d", &num);while (num != 0){if (num % 2 == 0){n_even++;sum_even += num;} //计算偶数个数和偶数和else{n_odd++;sum_odd +=num;} //计算奇数个数和奇数和scanf("%d",&num);}printf("The number of even numbers is %d, ""and the everage of even numbers is %.2f\n",n_even, (n_even == 0) ? 0 : (float)sum_even / n_even); printf("The number of odd numbers is %d, ""and the everrage of odd numers is %.2f\n",n_odd, (n_odd == 0) ? 0 : (float)sum_odd / n_odd);return 0;}4.#include <stdio.h>int main(void){char ch;int n_repl = 0; //替换次数printf("Enter some texts(# to quit):\n");while ((ch = getchar()) != '#') {if (ch == '.'){ch = '!';n_repl++;} //替换句号else if (ch == '!'){printf("!");n_repl++;} //替换感叹号printf("%c", ch);}printf("\n%d substitutions were made.\n", n_repl);return 0;}5.#include <stdio.h>int main(void){char ch;int n_repl = 0; //替换次数printf("Enter some texts(# to quit):\n");while ((ch = getchar()) != '#') {switch (ch){case '.': ch = '!';n_repl++;break;case '!': printf("!");n_repl++;break;default: break;} //利用switch语句进行替换 printf("%c",ch);}printf("\n%d substitutions were made.\n", n_repl);return 0;}6.#include <stdio.h>int main(void){char ch;char last_ch = 0; //前一个字符int count=0;printf("Enter some texts(# to quit):\n");while ((ch = getchar()) != '#'){if ((ch == 'i') && (last_ch == 'e'))count++;last_ch = ch; //出现ei时,计数+1}printf("\"ei\" appeared %d times.\n", count);return 0;}7.#include <stdio.h>#define BASE 1000 //基本工资 100美元/h#define TIME 40 //超过40h为加班#define MUL 1.5 //加班时间算作平时的1.5倍#define RATE1 0.15 //前300美元的税率#define RATE2 0.2 //300-450美元的税率#define RATE3 0.25 //大于450美元的税率#define BREAK1 300 //税率的第一个分界点#define BREAK2 450 //税率的第二个分界点int main(void){double hour, tax, gross;printf("Input your work hours in a week: ");scanf("%lf", &hour);if (hour <= TIME)gross = hour * BASE;elsegross = TIME * BASE + (hour - TIME) * MUL * BASE; //计算总收入if (gross <= BREAK1)tax = gross * RATE1;else if (gross <= BREAK2)tax = BREAK1 * RATE1 + (gross - BREAK1) * RATE2;elsetax = BREAK1 * RATE1 + (BREAK2 - BREAK1) * RATE2+ (gross - BREAK2) * RATE3;//计算税金printf("Your gross income is $%.2lf\nYour tax is $%.2lf\n""Your net income is $%.2lf\n",gross, tax, (gross - tax));return 0;8.#include <stdio.h>#define BASE1 8.75#define BASE2 9.33#define BASE3 10.00#define BASE4 11.20//四种等级的基本工资#define TIME 40 //超过40h为加班#define MUL 1.5 //加班时间算作平时的1.5倍#define RATE1 0.15 //前300美元的税率#define RATE2 0.2 //300-450美元的税率#define RATE3 0.25 //大于450美元的税率#define BREAK1 300 //税率的第一个分界点#define BREAK2 450 //税率的第二个分界点int main(void){double base, hour, tax, gross;int count, num;const int LENGTH = 65; //*的长度printpart: for (count = 0; count < LENGTH; count++)printf("*");printf("\nEnter the number corresponding to the desired pay rate or action:\n");printf("%-36s%s","1) $8.75/hr", "2) $9.33/hr\n");printf("%-36s%s","3) $10.00/hr", "4) $11.20/hr\n");printf("%s\n", "5) quit");for (count = 0; count < LENGTH; count++)printf("*");printf("\n");//打印表格while (scanf("%d", &num) == 1) {switch (num){case 1: base = BASE1;break;case 2: base = BASE2;break;case 3: base = BASE3;break;case 4: base = BASE4;break;case 5: printf("quit.\n");return 0;default: printf("Please input the right option.\n");goto printpart;} //选择基本工资等级printf("Input your work hours in a week: ");scanf("%lf", &hour);if (hour <= TIME)gross = hour * base;elsegross = TIME * base + (hour - TIME) * MUL * base;//计算总收入if (gross <= BREAK1)tax = gross * RATE1;else if (gross <= BREAK2)tax = BREAK1 * RATE1 + (gross - BREAK1) * RATE2;elsetax = BREAK1 * RATE1 + (BREAK2 - BREAK1) * RATE2+ (gross - BREAK2) * RATE3;//计算税金printf("Your gross income is $%.2lf\nYour tax is $%.2lf\n" "Your net income is $%.2lf\n",gross, tax, (gross - tax));printf("\nYour next choice:\n");}return 0;}9.#include <stdio.h>int main(void){int div, prime;int num, count;int flag;printf("Input a positive integer: ");scanf("%d", &num);printf("The prime numbers in range:\n");for (prime = 2; prime <= num; prime++) //外层循环显示所有素数 {flag = 1;for (div = 2; (div * div) <= prime; div++){if (prime % div == 0)flag = 0;} //内层循环检验是否为素数 if (flag) //利用标记flag判断printf("%d ",prime);}printf("\n");return 0;}10.#include <stdio.h>#define RATE1 0.15#define RATE2 0.28#define SINGLE 17850 //单身人群的税率分界点#define HOST 23900 //户主人群的税率分界点#define MAR_SHA 29750 //已婚共有人群的分界点#define MAR_DEV 14875 //已婚离异人群的分界点int main(void){int num;double income, tax_break, tax;printpart: printf("Please enter Corresponding""figures to select the type\n");printf("1 single, 2 host, 3 married and shared, ""4 married but devoced and 5 to quit.\n");scanf("%d", &num);switch (num){case 1: tax_break = SINGLE;break;case 2: tax_break = HOST;break;case 3: tax_break = MAR_SHA;break;case 4: tax_break = MAR_DEV;break;case 5: printf("quit.\n");return 0;default: printf("Please input right number.");goto printpart; //回到输入阶段}printf("Enter your income: "); //指定种类和收入while (scanf("%lf", &income) == 1){if (income <= tax_break)tax = income * RATE1;elsetax = tax_break * RATE1 + (income - tax_break) * RATE2; //计算税金printf("The tax is $%.2lf.\n", tax);printf("Your next input: \n");goto printpart; //回到输入阶段}return 0;}11.#include <stdio.h>#include <ctype.h>#define ARTICHOKE 2.05 //洋蓟2.05美元/磅#define BEET 1.15 //甜菜1.15美元/磅#define CARROT 1.09 //胡萝卜1.09美元/磅#define DISCOUNT_LIMIT 100//包装费和运费打折要求订单100美元#define DISCOUNT_RATE 0.05 //折扣为%5#define BREAK1 5#define BREAK2 20 //装运费的分界点#define FEE1 6.5#define FEE2 14#define FEE3_RATE 0.5//不同重量区间的装运费,其中超过20磅的每续重一磅//增加0.5元int main(void){double weight;double weight_artichoke = 0;double weight_beet = 0;double weight_carrot = 0; //购买三种蔬菜的重量double total_weight; //总重量double veg_cost; //三种蔬菜总共花费double order_cost; //订单总额double total_cost; //费用总额double pack_tran_fee; //装运费double discount;int count = 0;char ch;printf("Please select the vegetables you want to buy:\n");printf("a: artichoke $%.2f/lb\n", ARTICHOKE);printf("b: beet $%.2f/lb\n", BEET);printf("c: carrot $%.2f/lb\n", CARROT);printf("q: quit.\n");//打印选择信息while ((ch = tolower(getchar())) != 'q'){// if (ch == '\n')// continue; //滤掉回车switch (ch){case 'a': printf("Input the weight of artichoke in pound: "); scanf("%lf", &weight);weight_artichoke += weight;count++;printf("Continue entering a, b, c or q: ");break;case 'b': printf("Input the weight of beet in pound: ");scanf("%lf", &weight);weight_beet += weight;count++;printf("Continue entering a, b, c or q: ");break;case 'c': printf("Input the weight of carrot in pound: ");scanf("%lf", &weight);weight_carrot += weight;count++;printf("Continue entering a, b, c or q: ");break;default: printf("Please enter the right character.");}while (getchar () != '\n')continue; //滤掉输入重量后面的所有字符}if (!count){printf("Bye.\n");return 0;} //开始输出q,直接退出total_weight = weight_artichoke + weight_beet + weight_carrot;veg_cost = weight_artichoke * ARTICHOKE + weight_beet * BEET+ weight_carrot * CARROT;discount = 0;if (veg_cost >= DISCOUNT_LIMIT){discount = veg_cost * DISCOUNT_RATE;order_cost = veg_cost - discount;}elseorder_cost = veg_cost; //折扣计算if (total_weight <= BREAK1)pack_tran_fee = FEE1;else if (total_weight <= BREAK2)pack_tran_fee = FEE2;elsepack_tran_fee = FEE2 + (total_weight - BREAK2) * FEE3_RATE;//装运费计算total_cost = order_cost + pack_tran_fee;printf("\nHere is what you choose:\n");if (weight_artichoke) {printf("artichoke Price: $%.2f/lb weight: %.2f pounds cost: $%.2f\n",ARTICHOKE, weight_artichoke, weight_artichoke * ARTICHOKE); }if (weight_beet) {printf("beet Price: $%.2f/lb weight: %.2f pounds cost: $%.2f\n",。

C++Primer Plus 中文版第六版课后题第九章内存模型与名称空间

C++Primer Plus 中文版第六版课后题第九章内存模型与名称空间

1.golf.hconst int Len = 40;struct golf{char fullname[Len];int handicap;};void setgolf(golf & g, const char * nane, int hc); int setgolf(golf & g);void handicap(golf & g, int hc);void showgolf(const golf & g);g olf.cpp#include<iostream>#include "golf.h"using namespace std;void setgolf(golf & g, const char * name, int hc) {strncpy_s(g.fullname, name, Len);g.handicap = hc;}int setgolf(golf & g){cout << "Enter Golfers' fullname " ;cin.get(g.fullname, Len);if(g.fullname[0] == '\0')return 0;cout << "Enter Golfers' handicap " ;while(!(cin >> g.handicap)){cin.clear();while(cin.get() != '\n')continue;cout << "Please enter an integer: " ;}cin.get();return 1;}void handicap(golf & g, int hc){g.handicap = hc;}void showgolf(const golf & g){cout << "Fullname : " << g.fullname << ", Handicap : " << g.handicap << endl;}main.cpp#include<iostream>#include "golf.h"using namespace std;const int Men = 5;int main(){golf Golfer[Men];int i; //方¤?便À?下?面?读¨¢取¨?for(i = 0; i < Men; i++){if(setgolf(Golfer[i]) == 0)break;}for(int j = 0; j < i; j++) // int i 的Ì?作Á¡Â用®?showgolf(Golfer[j]);golf ann;setgolf(ann, "Ann Birdfree", 24);showgolf(ann);handicap(ann, 22);showgolf(ann);return 0;}2.#include<iostream>#include<string>using namespace std;void strcount(const string );int main(){string input;cout << "Enter a line: ";getline(cin, input);while(input != ""){strcount(input);cout << "Enter next line: " << endl;getline(cin, input);}cout << "Bye" << endl;return 0;}void strcount(const string str){static int total = 0;int count;cout << "\"" << str << "\" contains ";count = str.size();total += count;cout << count << " characters." << endl;cout << total << " total characters." << endl; }3.#include<iostream>#include<new>using namespace std;struct chaff{char dross[20];int slag;int main(){chaff * p = new chaff[2];strcpy_s(p[0].dross, "Good");p[0].slag = 23;strcpy_s(p[1].dross, "Great");p[1].slag = 233;for(int i = 0; i < 2; i++)cout << "#" << i+1 <<" dross: " << p[i].dross << ", slag: " << p[i].slag << endl;return 0;}4.s ales.hnamespace SALES{const int QUARTERS = 4;struct Sales{double sales[QUARTERS];double average;double max;double min;};void setSales(Sales & s, const double ar[], int n);void setSales(Sales & s);void showSales(const Sales & s);sales.cpp#include<iostream>#include"sales.h"namespace SALES{using std ::cout;using std ::cin;using std ::endl;static double salesaverage(const double arr[], int arrsize) {double sum = 0;for(int i = 0; i < arrsize; i++)sum += arr[i];return (sum/arrsize);}static double salesmax(const double arr[], unsigned arrsize) {double max = arr[0];for (int i =1; i < arrsize; i++){if(max < arr[i])max = arr[i];elsemax;}return max;}static double salesmin(const double arr[], unsigned arrsize)double min = arr[0];for (int i =1; i < arrsize; i++){if(min > arr[i])min = arr[i];elsemin;}return min;}void setSales(Sales & s, const double ar[], int n){unsigned times = n < QUARTERS ? (unsigned) n:QUARTERS;for (int i = 0; i < times; i++)s.sales[i] = ar[i];for (int i = times; i < QUARTERS; i++)s.sales[i] = 0;s.average = salesaverage(s.sales, times);s.max = salesmax(s.sales, times);s.min = salesmin(s.sales, times);}void setSales(Sales & s){cout << "Enter 4 sales: " << endl;for (int i = 0; i < QUARTERS; i++){cout << "# " << i+1 << " : ";cin >> s.sales[i];}s.average = salesaverage(s.sales, QUARTERS);s.max = salesmax(s.sales, QUARTERS);s.min = salesmin(s.sales, QUARTERS);}void showSales(const Sales & s){cout << "Sales: " << endl;for (int i = 0; i < QUARTERS; i++){cout << "# " << i+1 << " : " << s.sales[i] <<endl;}cout << "average: " << s.average << endl;cout << "max: " << s.max << endl;cout << "min: " << s.min << endl;}}main.cpp#include<iostream>#include"sales.h"using namespace std;int main(){using namespace SALES;Sales A, B;double hc[4] = {1.2, 2.3, 3.4, 4.5};cout <<"Show A" << endl;setSales(A, hc, 5);showSales(A);cout <<"Show B" << endl;setSales(B);showSales(B);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段,在这个文件中不要求写出该函数定义。

相关文档
最新文档