C Primer Plus中文版 (第5版) 课后习题答案
- 格式:pdf
- 大小:496.73 KB
- 文档页数:195
第二章:开始学习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 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=new car[num];for(int i=0;i<num;++i){cout<<"Car #"<<i+1<<":\n";cout<<"Please enter the make: ";getline(cin,ps[i].name);cout<<"Please enter 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;}n";return 0;}n";return 0;};for(int k=0;k<=i;++k)cout<<"*";cout<<endl;}return 0;}。
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 (inti = 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<<"个字符在这个文件中。
Chapter 2PE 2-1/* Programming Exercise 2-1 */#include <stdio.h>int main(void){printf("Anton Bruckner\n");printf("Anton\nBruckner\n");printf("Anton ");printf("Bruckner\n");return 0;}PE 2-3/* Programming Exercise 2-3 */#include <stdio.h>int main(void){int ageyears; /* age in years */int agedays; /* age in days *//* large ages may require the long type */ageyears = 44;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);int main(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-5/* Programming Exercise 2-5 */#include <stdio.h>int main(void){int toes;toes = 10;printf("toes = %d\n", toes);printf("Twice toes = %d\n", 2 * toes);printf("toes squared = %d\n", toes * toes);return 0;}/* or create two more variables, set them to 2 * toes and toes * toes */PE 2-7/* Programming Exercise 2-7 */#include <stdio.h>void one_three(void);void two(void);int main(void){printf("starting now:\n");one_three();printf("done!\n");return 0;}void one_three(void){printf("one\n");two();printf("three\n");}void two(void){printf("two\n");}Chapter 3PE 3-2/* Programming Exercise 3-2 */#include <stdio.h>int main(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>int main(void){float num;printf("Enter a floating-point value: ");scanf("%f", &num);printf("fixed-point notation: %f\n", num);printf("exponential notation: %e\n", num);return 0;}PE 3-6/* Programming Exercise 3-6 */#include <stdio.h>int main(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 4PE 4-1/* Programming Exercise 4-1 */#include <stdio.h>int main(void){char fname[40];char lname[40];printf("Enter your first name: ");scanf("%s", fname);printf("Enter your last name: ");scanf("%s", lname);printf("%s, %s\n", lname, fname);return 0;}PE 4-4/* Programming Exercise 4-4 */#include <stdio.h>int main(void){float height;char name[40];printf("Enter your height in inches: ");scanf("%f", &height);printf("Enter your name: ");scanf("%s", name);printf("%s, you are %.3f feet tall\n", name, height / 12.0);return 0;}PE 4-6/* Programming Exercise 4-6 */#include <stdio.h>#include <float.h>int main(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 5PE 5-1/* Programming Exercise 5-1 */#include <stdio.h>int main(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>int main(void){const int daysperweek = 7;int days, weeks, day_rem;printf("Enter the number of days: ");scanf("%d", &days);weeks = days / daysperweek;day_rem = days % daysperweek;printf("%d days are %d weeks and %d days.\n", days, weeks, day_rem);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);return 0;}PE 5-7/* Programming Exercise 5-7 */#include <stdio.h>void showCube(double x);int main(void) /* finds cube of entered number */{double val;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 6PE 6-1/* pe6-1.c *//* this implementation assumes the character codes *//* are sequential, as they are in ASCII. */#include <stdio.h>#define SIZE 26int main( void ){char lcase[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>int main( 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-5/* pe6-5.c */#include <stdio.h>int main( void ){int lower, upper, index;int square, cube;printf("Enter starting integer: ");scanf("%d", &lower);printf("Enter ending 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;}6-6 编写一个程序把一个单词读入一个字符数组,然后反向打印出这个词.#include <stdio.h>#include <string.h>int main(void){char word[256];int len;int i;printf("Please input a word(length max is 256):");scanf("%s",word);if((len = strlen(word)) > 256){printf("word is too long...\n");return 0;}printf("The word is %s\n",word);printf("End to start:");for(i=len; i>=0;i--)printf("%c",word[i]);printf("\n");return 0;}PE 6-7/* pe6-7.c */#include <stdio.h>int main( void ){double n, m;double res;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-10/* pe6-10.c */#include <stdio.h>#define SIZE 8int main( void ){int vals[SIZE];int i;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-12/* pe6-12.c *//* This version starts with the 0 power */#include <stdio.h>#define SIZE 8int main( 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-13/* pe-13.c *//* Programming Exercise 6-13 */#include <stdio.h>#define SIZE 8int main(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]);/* or scanf("%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-15/* pe6-15.c */#include <stdio.h>#define RATE_SIMP 0.10#define RATE_COMP 0.05#define INIT_AMT 100.0int main( 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 7PE 7-1/* Programming Exercise 7-1 */#include <stdio.h>int main(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++;elseother++;}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>int main(void){int n;double sumeven = 0.0;int ct_even = 0;double sumodd = 0.0;int ct_odd = 0;while (scanf("%d", &n) == 1 && n != 0){if (n % 2 == 1){sumodd += n;++ct_odd;}else{sumeven += n;++ct_even;}}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>int main(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 replacements of . with !\n", ct1);printf("%d replacements 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 */ int main(void){double hours;double gross;double net;double taxes;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/* Programmming Exercise 7-9 */#include <stdio.h>#define NO 0#define YES 1int main(void){long num; /* value to be checked */long div; /* potential divisors */long lim; /* limit to values */int prime;printf("Please enter limit to values to be checked; ");printf("Enter q to quit.\n");while (scanf("%ld", &lim) == 1 && lim > 0){for (num = 2; num <= lim; num++){for (div = 2, prime = YES; (div * div) <= num; div++)if (num % div == 0)prime = NO; /* number is not prime */if (prime == YES)printf("%ld is prime.\n", num);}printf("Please enter another limit; ");printf("Enter q to quit.\n");}return 0;}PE 7-11/* pe7-11.c *//* Programming Exercise 7-11 */#include <stdio.h>#include <ctype.h>int main(void){const double price_artichokes = 1.25;const double price_beets = 0.65;const double price_carrots = 0.89;const double DISCOUNT_RATE = 0.05;char ch;double lb_artichokes;double lb_beets;double lb_carrots;double lb_total;double cost_artichokes;double cost_beets;double cost_carrots;double cost_total;double final_total;double discount;double shipping;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_artichokes);break;case 'b' : printf("Enter pounds of beets: ");scanf("%lf", &lb_beets);break;case 'c' : printf("Enter pounds of carrots: ");scanf("%lf", &lb_carrots);break;default : printf("%c is not a valid choice.\n");}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 = 3.50;else if (lb_total < 20)shipping = 10.0;elseshipping = 8.0 + 0.1 * lb_total;if (cost_total > 100.0)discount = DISCOUNT_RATE * cost_total;elsediscount = 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 of carrots at $%.2f per pound: $%.2f\n",lb_carrots, price_carrots, cost_carrots);printf("Total cost of vegetables: $%.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 8PE 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 ASCII coding */#include <stdio.h>#include <ctype.h>int main(void){int ch;int uct = 0;int lct = 0;while ((ch = getchar()) != EOF)if (isupper(ch))uct++;else if (islower(ch))lct++;printf("%d uppercase characters read\n", uct);printf("%d lowercase characters read\n", lct);return 0;}/*or you could useif (ch >= 'A' && ch <= 'Z')uct++;else if (ch >= 'a' && ch <= 'z')lct++;*/PE 8-5/* Programming Exercise 8-5 *//* binaryguess.c -- an improved number-guesser */#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("\na h if it is high, and with an l if it is low.\n");printf("Uh...is your number %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>#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 tier */int getfirst(void);void menu(void);int main(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 number 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){int ch;ch = getchar();while (isspace(ch))ch = getchar();while (getchar() != '\n')continue;return ch;}Chapter 9PE 9-1/* Programming Exercise 9-1 */#include <stdio.h>double min(double a, double b);int main(void){double x, y;printf("Enter two numbers (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 implementationdouble min(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);int main(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;}void chLineRow(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);int main(void){double x, y;printf("Enter two numbers (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){double temp = *p1 > *p2 ? *p1 : *p2;*p1= *p2 = temp;}PE 9-7/* Programming Exercise 9-7 */#include <stdio.h>double power(double a, int b); /* ANSI prototype */int main(void){double x, xpow;int n;printf("Enter a number and the integer power");printf(" to which\nthe number 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 to quit.\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-9/* Programming Exercise 9-9 */#include <stdio.h>void to_base_n(int x, int base);int main(void){int number;int b;printf("Enter an integer (q to quit):\n");while (scanf("%d", &number) == 1){printf("Enter number base (2-10): ");scanf("%d", &b);printf("Base %d equivalent: ", b);to_base_n(number, b);putchar('\n');printf("Enter an integer (q to quit):\n");}return 0;}void to_base_n(int x, int base) /* recursive function */{int r;r = x % base;if (x >= 2)to_base_n(x / base, base);putchar('0' + r);return;}Chapter 10PE 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 */int main(void){/* initializing rainfall data for 1990 - 1994 */const float rain[YRS][MONTHS] = {{10.2, 8.1, 6.8, 4.2, 2.1, 1.8, 0.2, 0.3, 1.1, 2.3, 6.1, 7.4}, {9.2, 9.8, 4.4, 3.3, 2.2, 0.8, 0.4, 0.0, 0.6, 1.7, 4.3, 5.2}, {6.6, 5.5, 3.8, 2.8, 1.6, 0.2, 0.0, 0.0, 0.0, 1.3, 2.6, 4.2}, {4.3, 4.3, 4.3, 3.0, 2.0, 1.0, 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.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", 1990 + 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;int max = 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 10float max_diff(const float ar[], int n);void show_arr(const float ar[], int n);int main(void){float orig[LEN] = {1.1,2,3,4,12,6,7,8,9,10}; float max;show_arr(orig, LEN);max = max_diff(orig, LEN);printf("%g = maximum difference\n", max);return 0;}float max_diff(const float ar[], int n){int i;float max = ar[0];float min = 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 float ar[], int n){int i;for (i = 0; i < n; i++)printf("%g ", ar[i]);putchar('\n');}PE 10-7/* Programming Exercise 10-7 */#include <stdio.h>#define LEN1 7#define LEN2 3void copy_arr(int ar1[], const int ar2[], int n); void show_arr(const int ar[], int n);int main(void){int orig[LEN1] = {1,2,3,4,5,6,7};int copy[LEN2];。
C程序设计(第五版)-第4章选择结构程序设计课后习题答案1. 什么是算术运算?什么是关系运算?什么是逻辑运算?【答案解析】算熟运算:算术运算即“四则运算”,是加法、减法、乘法、除法、乘⽅、开⽅等⼏种运算的统称。
其中加减为⼀级运算,乘除为⼆级运算,乘⽅、开⽅为三级运算。
在⼀道算式中,如果有多级运算存在,则应先进⾏⾼级运算,再进⾏低⼀级的运算。
C语⾔中的算熟运算符包括:+、-、*、/、++、--、%等种类。
如果只存在同级运算;则从左⾄右的顺序进⾏;如果算式中有括号,则应先算括号⾥边,再按上述规则进⾏计算。
⽰例:$ (1 + 1)^{2} * 4+5 * 3$解析:1. 先进⾏括号内运算1+1,然后进⾏乘⽅运算得到结果4.2. 接下来与4相乘,得到结果163. 因为乘法优先级⼤于加法,因此先进⾏5*3,得到结果154. 最终相加得到结果31结果:31关系运算:关系的基本运算有两类:⼀类是传统的集合运算(并、差、交等),另⼀类是专门的关系运算(选择、投影、连接、除法、外连接等),⽽在C语⾔中,关系运算通常被认为是⽐较运算,将两个数值进⾏⽐较,判断⽐较结果是否符合给定的条件。
常见的关系运算符包括:<、<=、>、>=、==、!=等种类。
其中,前4种关系运算符(<、<=、>、>= )的优先级别相同,后2种(==、!=)也相同。
⽽前4种⾼于后2种。
例如, >优先于==。
⽽>与<优先级相同。
并且,关系运算符的优先级低于算术运算符,关系运算符的优先级⾼于赋值运算符(=)。
逻辑运算:在逻辑代数中,有与、或、⾮三种基本逻辑运算。
表⽰逻辑运算的⽅法有多种,如语句描述、逻辑代数式、真值表、卡诺图等。
⽽在C语⾔中,逻辑运算通常⽤于使⽤逻辑运算符将关系表达式或其它逻辑量连接起来组成逻辑表达式⽤来测试真假值。
常见的逻辑运算符包括:&&、||、!等种类&&:与是双⽬运算符,要求有两个运算对象,表⽰两个运算对象都成⽴,则结果为真,否则结果为假。
《C++Primer》第五版习题答案--第⼀章【学习笔记】C++Primer第五版习题解答---第⼀章ps:答案是个⼈在学习过程中书写,可能存在错漏之处,仅作参考。
作者:cosefyDate: 2022/1/7第⼀章:开始练习1.3#include<iostream>int main() {std::cout << "hello, world" << std::endl;return 0;}练习1.4:#include<iostream>int main(){int v1 = 0, v2 = 0;std::cout << "please input two numbers: " << std::endl;std::cin >> v1 >> v2;std::cout << "The product of " << v1 << " and " << v2 << " is: " << v1 * v2 << std::endl;return 0;}练习1.5:#include<iostream>int main(){int v1 = 0, v2 = 0;std::cout << "please input two numbers: " << std::endl;std::cin >> v1 >> v2;std::cout << "The product of ";std::cout << v1;std::cout << " and ";std::cout << v2;std::cout << " is: ";std::cout << v1 * v2;std::cout << std::endl;return 0;}练习1.6:结果如下图所⽰,存在报错,显然格式不合法。
C_primer_plus(第五版)(完整)@第一章概览编程练习1.您刚刚被MacroMuscle有限公司(Software for Hard Bodies)聘用。
该公司要进入欧洲市场,需要一个将英寸转换为厘米(1英寸=2.54 cm)的程序。
他们希望建立的该程序可提示用户输入英寸值。
您的工作是定义程序目标并设计该程序(编程过程的第1步和第2步)。
1.将英寸值转化为厘米值2.显示“输入英寸值”->得到该值->转换为厘米值->存储->告知用户已结束第二章 C语言概述编程练习1.编写一个程序,调用printf()函数在一行上输出您的名和姓,再调用一次printf()函数在两个单独的行上输出您的名和姓,然后调用一对printf()函数在一行上输出您的名和姓。
输出应如下所示(当然里面要换成您的姓名):Anton BrucknerAntonBrucknerAnton Bruckner第一个输出语句第二个输出语句仍然是第二个输出语句第三个和第四个输出语句#include<stdio.h>int main(void){printf("He Jin\n");printf("He\n");printf("Jin\n");printf("He Jin\n");return(0);}2.编写一个程序输出您的姓名及地址。
#include<stdio.h>int main(void) //此处不可加;{printf("Name:He Jin\n");printf("Address:CAUC\n");return(0);}3.编写一个程序,把您的年龄转换成天数并显示二者的值。
不用考虑平年( fractional year)和闰年(leapyear)的问题。
#include<stdio.h>int main(void){int age=22;printf("Age:%d\n",age);printf("Day:%d\n",age*356);return(0);}4.编写一个能够产生下面输出的程序:For he's a jolly good fellow!For he's a jolly good fellow!For he's a jolly good fellow!Which nobody can deny!程序中除了main()函数之外,要使用两个用户定义的函数:一个用于把上面的夸奖消息输出一次:另一个用于把最后一行输出一次。
C PRIMER PLUS 第五章正确答案.txtPE 5-1/* Programming Exercise 5-1 */#include <stdio.h>int main(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>int main(void){const int daysperweek = 7;int days, weeks, day_rem;printf("Enter the number of days: ");scanf("%d", &days);weeks = days / daysperweek;day_rem = days % daysperweek;printf("%d days are %d weeks and %d days.\n", days, weeks, day_rem);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);return 0;}PE 5-7/* Programming Exercise 5-7 */#include <stdio.h>void showCube(double x);int main(void) /* finds cube of entered number */{double val;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 );}#include <stdio.h>void Temperatures(double f);int main (void) {double a;printf("input a float Fahrenheit ,and this program will output centigrade and kelvin\n");printf("enter q or other character to quit\n");while(scanf("%lf",&a) == 1) {Temperatures((double)a);}printf("done!\n");return 0;}void Temperatures(double f) {double c,k;c = 1.8 * f + 32.0;k = c + 273.16;printf("%.2f f = %.2f c = %.2f k\n",f,c,k);}。
C++Primer第5版第⼗五章课后练习答案练习15.1成员函数应在其声明之前动态绑定。
基类中的虚成员希望其派⽣类定义其⾃⼰的版本。
特别是基类通常应定义虚析构函数,即使它不起作⽤。
练习15.2派⽣类能访问基类的共有成员⽽不能访问私有成员,但派⽣类能访问基类的protected访问运算符描述的成员,⽽禁⽌其它⽤户访问练习15.3#include <string>#include <iostream>#ifndef _QUOTE_H_#define _QUOTE_H_class Quote{public:Quote()=default;Quote(const std::string& book, double sales_price) :bookNo(book), price(sales_price) {}std::string isbn() const { return bookNo; }virtual double net_price(std::size_t n)const { return n * price; }virtual ~Quote() = default;private:std::string bookNo;protected:double price = 0.0;};double print_total(std::ostream& os, const Quote& item, size_t n){double ret = _price(n);os << "ISBN: " << item.isbn() << " # sold: " << n << " total due: " << ret << std::endl;return ret;}#endif// !_QUOTE_H_练习15.4class Base { ... };(a) class Derived : public Derived { ... }; // 错误,类重复定义,不能⾃⼰继承⾃⼰(b) class Derived : private Base { ... }; // 正确(c) class Derived : public Base; // 错误,类的声明包含类名但不包含类派⽣列表练习15.5class Bulk_quote:public Quote{public:Bulk_quote() = default;Bulk_quote(const std::string&, double, std::size_t,double);double net_price(std::size_t)const override;protected:std::size_t min_qty = 0;double discount = 0.0;};Bulk_quote::Bulk_quote(const std::string& book, double p, std::size_t qty,double disc) :Quote(book, p), min_qty(qty), discount(disc) {}inline double Bulk_quote::net_price(std::size_t cnt) const{if (cnt >= min_qty)return cnt * (1 - discount) * price;elsereturn cnt * price;}练习15.6int main(int argc, char* argv[]){Bulk_quote bq;Quote q(bq);print_total(cout, q, 1);print_total(cout, bq, 1);return0;}练习15.7class Limit_quote : public Bulk_quote{public:Limit_quote() = default;Limit_quote(const std::string&, double, std::size_t, std::size_t, double);double net_price(std::size_t)const override;private:std::size_t max_qty = 0;};Limit_quote::Limit_quote(const std::string& book, double p, std::size_t min, std::size_t max,double disc) :Bulk_quote(book, p,min,disc), max_qty(max){}inline double Limit_quote::net_price(std::size_t cnt) const{if(cnt>=max_qty)return max_qty * (1 - discount) * price+(cnt- max_qty)*price;else if (cnt >= min_qty)return cnt * (1 - discount) * price;elsereturn cnt * price;}练习15.8静态类型:在编译时总是已知的,它是变量声明时的类型或表达式⽣成的类型动态类型:变量或表达式表⽰的内存中的对象的类型。
C++Primer第5版第⼗四章课后练习答案练习14.1区别: 1.可以直接调⽤重载的运算符 2.⾄少有⼀个运算对象是类类型 3.⽆法保留运算对象的求值顺序规则和短路求值规则共同点: 重载运算符的优先级和结合律与对应的内置运算符保持⼀致练习14.2#ifndef SALES_DATA_H#define SALES_DATA_H#include <string>#include <ostream>using std::string;using std::istream;using std::ostream;using std::endl;class Sales_data {friend istream& operator>>(istream& is, Sales_data& it);friend ostream& operator<<(ostream& os, Sales_data& it);private:string bookNo;unsigned units_sold = { 0 };double revenue = { 0.0 };public:const string& isbn() const { return bookNo; }Sales_data& operator+=(const Sales_data& rhs) {units_sold += rhs.units_sold;revenue += rhs.revenue;return *this;}Sales_data(string bn, unsigned us = 0, double re = 0.0) :bookNo(bn), units_sold(us), revenue(re) { std::cout << "Sales_data(string bn, unsigned us = 0, double re = 0.0)" << std::endl;} Sales_data() :Sales_data("") { std::cout << "Sales_data()" << std::endl; }Sales_data(istream& is) :Sales_data() { is>> *this; std::cout << "Sales_data(istream& is)" << std::endl; }};Sales_data operator+(Sales_data& lhs, Sales_data& rhs) {Sales_data sum = lhs;sum += rhs;return sum;}istream & operator>>(istream& is, Sales_data& it) {is >> it.bookNo >> it.units_sold >> it.revenue;return is;}ostream& operator<<(ostream& os, Sales_data& it) {os << it.isbn() << "" << it.units_sold << "" << it.revenue << endl;return os;}#endif// !SALES_DATA_H练习14.3"cobble" == "stone"; //两者元素中既不是string也不是vector,因此两个版本都不是svec1[0] == svec2[0]; //stringsvec1 == svec2; //vectorsvec1[0] == "stone"; //string练习14.4(a) % 算数运算符,通常为普通的⾮成员函数(b) %= 复合赋值运算符,通常为成员函数(c) ++ 改变对象状态的运算符,通常为成员函数(d) -> 必须是成员函数(e) << 通常为普通的⾮成员函数(f) && 通常为普通的⾮成员函数(g) == 通常为普通的⾮成员函数(h) () 必须是成员函数练习14.5#ifndef DATE_H_#define DATE_H_#include<string>using std::string;class Date{public:Date(string&);~Date();unsigned getYear()const { return year; }unsigned getMonth() const { return month; }unsigned getDay() const { return day; }private:unsigned year;unsigned month;unsigned day;void str_to_month(string &str,string::size_type& pos);};Date::Date(string &s){string::size_type pos1, pos2;if (pos1 = s.find_first_of(",/") == string::npos) {pos1 = s.find_first_of("");pos2 = s.find_last_of("");str_to_month(s, pos1);day = stoul(s.substr(pos1 + 1, pos2));year = stoul(s.substr(pos2 + 1, s.size()));}else if (pos1 = s.find_first_of(",") == string::npos) {pos1 = s.find_first_of("/");pos2 = s.find_last_of("/");str_to_month(s, pos1);day = stoul(s.substr(pos1 + 1, pos2));year = stoul(s.substr(pos2 + 1, s.size()));}else if (pos1 = s.find_first_of("/") == string::npos) {pos1 = s.find_first_of("");pos2 = s.find_last_of(",");str_to_month(s, pos1);day = stoul(s.substr(pos1 + 1, pos2));year = stoul(s.substr(pos2 + 1, s.size()));}else{day = month = year = 0;}}Date::~Date(){}inline void Date::str_to_month(string& s, string::size_type& pos1){if (s.substr(0, pos1) == "Jan" || s.substr(0, pos1) == "January") {month = 1;}else if (s.substr(0, pos1) == "Feb" || s.substr(0, pos1) == "February") { month = 2;}else if (s.substr(0, pos1) == "Mar" || s.substr(0, pos1) == "March") {month = 3;}else if (s.substr(0, pos1) == "Apr" || s.substr(0, pos1) == "April") {month = 4;}else if (s.substr(0, pos1) == "May" || s.substr(0, pos1) == "May") {month = 5;}else if (s.substr(0, pos1) == "Jun" || s.substr(0, pos1) == "June") {month = 6;}else if (s.substr(0, pos1) == "Jul" || s.substr(0, pos1) == "July") {month = 7;}else if (s.substr(0, pos1) == "Aug" || s.substr(0, pos1) == "August") {month = 8;}else if (s.substr(0, pos1) == "Sept" || s.substr(0, pos1) == "September") { month = 9;}else if (s.substr(0, pos1) == "Oct" || s.substr(0, pos1) == "October") {month = 10;}else if (s.substr(0, pos1) == "Nov" || s.substr(0, pos1) == "November") { month = 11;}else if (s.substr(0, pos1) == "Dec" || s.substr(0, pos1) == "December") { month = 12;}else {month = stoul(s.substr(0, pos1));}}std::ostream& operator<< (std::ostream& os,const Date& d){os << d.getYear() << "-" << d.getMonth() << "-" << d.getDay();return os;}练习14.6ostream& operator<<(ostream& os, const Sales_data& it) {os << it.isbn() << "" << it.units_sold << "" << it.revenue;return os;}练习14.7ostream& operator<<(ostream& os, const String& s){auto sl = s.begin();while (sl != s.end()) os << *(sl++);return os;}练习14.8std::ostream& operator<< (std::ostream& os,const Date& d){os << d.getYear() << "-" << d.getMonth() << "-" << d.getDay();return os;}练习14.9istream & operator>>(istream& is, Sales_data& it) {is >> it.bookNo >> it.units_sold >> it.revenue;if (!is)it = Sales_data();return is;}练习14.10(a)0-201-99999-9 10 24.950-201-99999-9 10 24.95(b)10 24.95 0-210-99999-910 24 0.95练习14.11没有输⼊检查,什么也不会发⽣练习14.12std::istream& operator>> (std::istream& is, Date& d){is >> d.year >> d.month >> d.day;if (!is) {std::string s = "";d = Date(s);}return is;}练习14.13还应该⽀持operator-运算符,因此也应该⽀持operator-=复合运算符Sales_data& operator-=(const Sales_data& rhs) {units_sold -= rhs.units_sold;revenue -= rhs.revenue;return *this;}Sales_data operator-(Sales_data& lhs, Sales_data& rhs) {Sales_data sum = lhs;sum -= rhs;练习14.14因为operator+=不需要创建临时空间,所以调⽤operator+=⽐其它⽅法更奏效练习14.15不是,因为Date类对于类对象的+-计算会产⽣⼆义性练习14.16StrBlob类,StrBlobPtr类inline bool operator==(const StrBlob& lhs, const StrBlob& rhs){return *lhs.data == *rhs.data;}inline bool operator!=(const StrBlob& lhs, const StrBlob& rhs){return !(lhs==rhs);}// named equality operators for StrBlobPtrinlinebool operator==(const StrBlobPtr &lhs, const StrBlobPtr &rhs){auto l = lhs.wptr.lock(), r = rhs.wptr.lock();// if the underlying vector is the sameif (l == r)// then they're equal if they're both null or// if they point to the same elementreturn (!r || lhs.curr == rhs.curr);elsereturn false; // if they point to difference vectors, they're not equal}inlinebool operator!=(const StrBlobPtr &lhs, const StrBlobPtr &rhs){return !(lhs==rhs);}// named equality operators for StrBlobPtrinlinebool operator==(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs){auto l = lhs.wptr.lock(), r = rhs.wptr.lock();// if the underlying vector is the sameif (l == r)// then they're equal if they're both null or// if they point to the same elementreturn (!r || lhs.curr == rhs.curr);elsereturn false; // if they point to difference vectors, they're not equal}inlinebool operator!=(const ConstStrBlobPtr& lhs, const ConstStrBlobPtr& rhs){return !(lhs==rhs);}StrVec类bool operator==(const StrVec& lhs, const StrVec& rhs){if (lhs.size() != rhs.size()) {return false;}else {for (auto l_iter = lhs.begin(),r_iter = rhs.begin(); l_iter != lhs.end(); ++l_iter, ++r_iter) {if (*l_iter != *r_iter) {return false;}}}return true;}inline bool operator!=(const StrVec& lhs, const StrVec& rhs){return !(lhs==rhs);}String类inline bool operator==(const String& lhs, const String& rhs){if (lhs.size() != rhs.size()) {else {for (auto l_iter = lhs.begin(), r_iter = rhs.begin(); l_iter != lhs.end(); ++l_iter, ++r_iter) {if (*l_iter != *r_iter) {return false;}}}return true;}inline bool operator!=(const String& lhs, const String& rhs){return !(lhs == rhs);}练习14.19inline bool operator==(const Date& lhs, const Date& rhs){return lhs.year==rhs.year&& lhs.month == rhs.month && lhs.day == rhs.day;}inline bool operator!=(const Date& lhs, const Date& rhs){return !(lhs == rhs);}练习14.20Sales_data& operator+=(const Sales_data& rhs) {units_sold += rhs.units_sold;revenue += rhs.revenue;return *this;}Sales_data operator+(Sales_data& lhs, Sales_data& rhs) {Sales_data sum = lhs;sum += rhs;return sum;}练习14.21Sales_data operator+(const Sales_data& lhs, const Sales_data& rhs) {Sales_data sum = lhs;sum.units_sold += rhs.units_sold;sum.revenue += rhs.revenue;return sum;}Sales_data& operator+=(const Sales_data& rhs) {const Sales_data tmp = *this;*this = tmp + rhs;return *this;}operator+=运算符调⽤operator+运算符前需要创建临时内存空间练习14.22Sales_data& Sales_data::operator=(string& s){bookNo = s;units_sold = 0;revenue = 0;}练习14.23inline StrVec& StrVec::operator=(std::initializer_list<std::string> il){auto newdata = alloc_n_copy(il.begin(), il.end());free();elements = newdata.first;first_free = cap = newdata.second;return *this;}练习14.24Date类不需要实现拷贝赋值和移动赋值运算符,因为Date类中只含有三个int变量,默认的浅拷贝就能满⾜要求。