c++primer plus 5thedition编程练习答案【非扫描】

65
//pe2-2.cpp #include<iostream> intmain(void) { usingnamespacestd; cout<<"Enteradistanceinfurlongs:"; doublefurlongs; cin>>furlongs; doublefeet; feet=220*furlongs; cout<<furlongs<<"furlongs=" <<feet<<"feet\n"; return0; } //pe2-3.cpp #include<iostream> usingnamespacestd; voidmice(); voidrun(); intmain() { mice(); mice(); run(); run(); return0; } voidmice() { cout<<"Threeblindmice\n"; } voidrun() { cout<<"Seehowtheyrun\n"; } //pe2-4.cpp #include<iostream> doubleC_to_F(double); intmain() { usingnamespacestd; cout<<"EnteratemperatureinCelsius:"; doubleC; cin>>C; doubleF; F=C_to_F(C);

Upload: rui-zhang

Post on 06-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 1/65

//pe2-2.cpp

#include<iostream>

intmain(void){usingnamespacestd;cout<<"Enteradistanceinfurlongs:";doublefurlongs;cin>>furlongs;doublefeet;feet=220*furlongs;cout<<furlongs<<"furlongs="<<feet<<"feet\n";

return0;}

//pe2-3.cpp

#include<iostream>usingnamespacestd;

voidmice();voidrun();intmain(){mice();mice();

run();run();

return0;}

voidmice(){cout<<"Threeblindmice\n";}

voidrun(){cout<<"Seehowtheyrun\n";}

//pe2-4.cpp

#include<iostream>

doubleC_to_F(double);intmain(){usingnamespacestd;cout<<"EnteratemperatureinCelsius:";doubleC;cin>>C;doubleF;F=C_to_F(C);

Page 2: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 2/65

cout<<C<<"degreesCelsius="<<F<<"degreesFahrenheit\n";

return0;

}

doubleC_to_F(doubletemp){return1.8*temp+32.0;}

//pe3-1.cpp

#include<iostream>

constintInch_Per_Foot=12;

intmain(void){

usingnamespacestd;//Note:someenvironmentsdon'tsupportthebackspacecharactercout<<"Pleaseenteryourheightininches:___/b/b/b";intht_inch;cin>>ht_inch;intht_feet=ht_inch/Inch_Per_Foot;intrm_inch=ht_inch%Inch_Per_Foot;cout<<"Yourheightis"<<ht_feet<<"feet,";cout<<rm_inch<<"inch(es).\n";return0;}

//pe3-3.cpp#include<iostream>constdoubleMINS_PER_DEG=60.0;constdoubleSECS_PER_MIN=60.0;intmain(){usingnamespacestd;

intdegrees;intminutes;intseconds;doublelatitude;

cout<<"Enteralatitudeindegrees,minutes,andseconds:\n";cout<<"First,enterthedegrees:";cin>>degrees;cout<<"Next,entertheminutesofarc:";cin>>minutes;cout<<"Finally,enterthesecondsofarc:";cin>>seconds;latitude=degrees+(minutes+seconds/SECS_PER_MIN)/MINS_PER_DEG;cout<<degrees<<"degrees,"<<minutes<<"minutes,"<<seconds<<"seconds="<<latitude<<"degrees\n";return0;}

Page 3: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 3/65

!

//pe3-5.cpp

#include<iostream>

intmain(void){usingnamespacestd;cout<<"Howmanymileshaveyoudrivenyourcar?";floatmiles;cin>>miles;cout<<"Howmanygallonsofgasolinedidthecaruse?";floatgallons;cin>>gallons;cout<<"Yourcargot"<<miles/gallons;cout<<"milespergallon.\n";return0;}

//pe3-6.cpp

#include<iostream>

constdoubleKM100_TO_MILES=62.14;constdoubleLITERS_PER_GALLON=3.875;

intmain(void){usingnamespacestd;doubleeuro_rating;doubleus_rating;cout<<"Enterfuelconsumptioninlitersper100km:";cin>>euro_rating;//dividebyLITER_PER_GALLONtogetgallonsper100-km 

//dividebyKM100_TO_MILEStogetgallonspermile//invertresulttogetmilespergallonus_rating=(LITERS_PER_GALLON*KM100_TO_MILES)/euro_rating;cout<<euro_rating<<"litersper100kmis";cout<<us_rating<<"milespergallon.\n";

return0;}

//pe4-2.cpp--storingstringsinstringobjects#include<iostream>#include<string>

intmain(){usingnamespacestd;stringname;stringdessert;

cout<<"Enteryourname:\n";getline(cin,name);//readsthroughnewlinecout<<"Enteryourfavoritedessert:\n";getline(cin,dessert);cout<<"Ihavesomedelicious"<<dessert;cout<<"foryou,"<<name<<".\n";return0;}

Page 4: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 4/65

//pe4-3.cpp--storingstringsinchararrays#include<iostream>#include<cstring>

constintSIZE=20;intmain(){usingnamespacestd;charfirstName[SIZE];charlastName[SIZE];charfullName[2*SIZE+1];

cout<<"Enteryourfirstname:";cin>>firstName;cout<<"Enteryourlastname:";cin>>lastName;strncpy(fullName,lastName,SIZE);strcat(fullName,",");strncat(fullName,firstName,SIZE);

fullName[SIZE-1]='\0';cout<<"Here'stheinformationinasinglestring:"<<fullName<<endl;return0;}

//pe4-5.cpp//acandybarstructurestructCandyBar{charbrand[40];doubleweight;intcalories;};

#include<iostream>

intmain(){usingnamespacestd;//introducesnamespacestdCandyBarsnack={"MochaMunch",2.3,350};

cout<<"Brandname:"<<snack.brand<<endl;cout<<"Weight:"<<snack.weight<<endl;cout<<"Calories:"<<snack.calories<<endl;

return0;}

//pe4-7.ccp

#include<iostream>

constintSlen=70;

structpizza{charname[Slen];floatdiameter;floatweight;};

intmain(void){

Page 5: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 5/65

usingnamespacestd;pizzapie;cout<<"Whatisthenameofthepizzacompany?";cin.getline(pie.name,Slen);

cout<<"Whatisthediameterofthepizzaininches?";cin>>pie.diameter;cout<<"Howmuchdoesthepizzaweighinounces?";cin>>pie.weight;cout<<"Company:"<<pie.name<<"\n";cout<<"Diameter:"<<pie.diameter<<"inches\n";cout<<"Weight:"<<pie.weight<<"ounces\n";return0;}

//pe5-2.cpp

#include<iostream>

intmain(void){usingnamespacestd;doublesum=0.0;doublein;cout<<"Enteranumber(0toterminate):";cin>>in;while(in!=0){sum+=in;

cout<<"Runningtotal="<<sum<<"\n";cout<<"Enternextnumber(0toterminate):";cin>>in;}cout<<"Bye!\n";return0;}

//pe5-4.cpp//booksales#include<iostream>

constintMONTHS=12;constchar*months[MONTHS]={"January","February","March","April",

"May","June","July","August","September","October","November","December"};intmain(){usingnamespacestd;//introducesnamespacestdintsales[MONTHS];intmonth;

cout<<"Enterthemonthlysalesfor\"C++forFools\":\n";for(month=0;month<MONTHS;month++){

cout<<"Salesfor"<<months[month]<<":";cin>>sales[month];}

Page 6: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 6/65

doubletotal=0.0;for(month=0;month<MONTHS;month++)total+=sales[month];

cout<<"Totalsales:"<<total<<endl;return0;}

//pe5-6.cpp

#include<iostream>

structcar{charname[20];intyear;};

intmain(void){usingnamespacestd;

intn;cout<<"Howmanycarsdoyouwishtocatalog?:";

cin>>n;

while(cin.get()!='\n')//getridofrestofline;

car*pc=newcar[n];

inti;for(i=0;i<n;i++){cout<<"Car#"<<(i+1)<<":\n";cout<<"Pleaseenterthemake:";

cin.getline(pc[i].name,20);cout<<"Pleaseentertheyearmade:";cin>>pc[i].year;while(cin.get()!='\n')//getridofrestofline;}cout<<"Hereisyourcollection:\n";for(i=0;i<n;i++)cout<<pc[i].year<<""<<pc[i].name<<"\n";

delete[]pc;return0;}

//pe5-7.cpp--countwordsusingC-stylestring

#include<iostream>#include<cstring>//prototypeforstrcmp()constintSTR_LIM=50;intmain(){usingnamespacestd;charword[STR_LIM];intcount=0;

cout<<"Enterwords(tostop,typetheworddone):\n";

while(cin>>word&&strcmp("done",word))++count;

Page 7: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 7/65

"

cout<<"Youenteredatotalof"<<count<<"words.\n";return0;}

//pe5-9.cpp//nestedloops

#include<iostream>

intmain(){usingnamespacestd;//introducesnamespacestdintrows;introw;intcol;intperiods;

cout<<"Enternumberofrows:";cin>>rows;

for(row=1;row<=rows;row++){periods=rows-row;for(col=1;col<=periods;col++)cout<<'.';//colalreadyhascorrectvaluefornextloopfor(;col<=rows;col++)cout<<'*';cout<<endl;}

return0;

}

//pe6-1.cpp#include<iostream>#include<cctype>intmain(){usingnamespacestd;//introducesnamespacestdcharch;

cin.get(ch);while(ch!='@'){if(!isdigit(ch)){if(isupper(ch))ch=tolower(ch);elseif(islower(ch))ch=toupper(ch);cout<<ch;}cin.get(ch);}

return0;}

Page 8: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 8/65

#

//pe6-3.cpp

#include<iostream>

intmain(void){usingnamespacestd;cout<<"Pleaseenteroneofthefollowingchoices:\n";cout<<"c)carnivorep)pianist\n"<<"t)treeg)game\n";charch;cin>>ch;while(ch!='c'&&ch!='p'&&ch!='t'&&ch!='g')

{cout<<"Pleaseenterac,p,t,org:";cin>>ch;}

switch(ch){case'c':cout<<"Acatisacarnivore.\n";break;case'p':cout<<"RaduLupuisapianist.\n";

break;case't':cout<<"Amapleisatree.\n";break;case'g':cout<<"Golfisagame.\n";break;default:cout<<"Theprogramshouldn'tgethere!\n";}return0;}

//pe6-5.cpp//Neutroniataxation#include<iostream>constdoubleLEV1=5000;constdoubleLEV2=15000;constdoubleLEV3=35000;constdoubleRATE1=0.10;constdoubleRATE2=0.15;constdoubleRATE3=0.20;intmain(){usingnamespacestd;

doubleincome;doubletax;

cout<<"Enteryourannualincomeintvarps:";cin>>income;

if(income<=LEV1)tax=0;elseif(income<=LEV2)tax=(income-LEV1)*RATE1;elseif(income<=LEV3)

tax=RATE1*(LEV2-LEV1)+RATE2*(income-LEV2);elsetax=RATE1*(LEV2-LEV1)+RATE2*(LEV3-LEV2)+RATE3*(income-LEV3);

cout<<"YouoweNeutronia"<<tax<<"tvarpsintaxes.\n";

Page 9: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 9/65

$

return0;}

//pe6-7.cpp#include<iostream>#include<string>intmain(){usingnamespacestd;stringword;charch;intvowel=0;intconsonant=0;intother=0;cout<<"Enterwords(qtoquit):\n";cin>>word;while(word!="q")

{ch=tolower(word[0]);if(isalpha(ch)){if(ch=='a'||ch=='e'||ch=='i'||ch=='o'

||ch=='u')vowel++;elseconsonant++;}elseother++;cin>>word;}cout<<vowel<<"wordsbeginningwithvowels\n";

cout<<consonant<<"wordsbeginningwithconsonants\n";cout<<other<<"others\n";

return0;}

//pe6-8.cpp--countingcharacters#include<iostream>#include<fstream>//fileI/Osuppport#include<cstdlib>//supportforexit()constintSIZE=60;intmain(){usingnamespacestd;charfilename[SIZE];charch;ifstreaminFile;//objectforhandlingfileinput

cout<<"Enternameofdatafile:";cin.getline(filename,SIZE);inFile.open(filename);//associateinFilewithafileif(!inFile.is_open())//failedtoopenfile{cout<<"Couldnotopenthefile"<<filename<<endl;cout<<"Programterminating.\n";exit(EXIT_FAILURE);}intcount=0;//numberofitemsread

Page 10: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 10/65

inFile>>ch;//getfirstvaluewhile(inFile.good())//whileinputgoodandnotatEOF{count++;//onemoreitemread

inFile>>ch;//getnextvalue}

cout<<count<<"charactersin"<<filename<<endl;

inFile.close();//finishedwiththefilereturn0;

}

//pe7-1.cpp--harmonicmean

#include<iostream>

doubleh_mean(doublex,doubley);

intmain(void){usingnamespacestd;doublex,y;

cout<<"Entertwonumbers(a0terminates):";while(cin>>x>>y&&x*y!=0)cout<<"harmonicmeanof"<<x<<"and"<<y<<"="<<h_mean(x,y)<<"\n";/*ordothereadingandtestingintwoparts:while(cin>>x&&x!=0){cin>>y;if(y==0)break;

...*/cout<<"Bye\n";return0;}

doubleh_mean(doublex,doubley){return2.0*x*y/(x+y);}

//pe7-3.cpp

#include<iostream>

structbox{charmaker[40];floatheight;floatwidth;floatlength;floatvolume;};

voidshowbox(boxb);

Page 11: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 11/65

voidsetbox(box*pb);

intmain(void){

boxcarton={"BingoBoxer",2,3,5};//novolumeprovidedsetbox(&carton);showbox(carton);return0;}

voidshowbox(boxb){usingnamespacestd;cout<<"Boxmaker:"<<b.maker<<"\nheight:"<<b.height<<"\nlwidth:"<<b.width<<"\nlength:"<<b.length<<"\nvolume:"<<b.volume<<"\n";}

voidsetbox(box*pb){pb->volume=pb->height*pb->width*pb->length;}

//pe7-4.cpp-- probability ofwinning#include<iostream>longdoubleprobability(unsignednumbers,unsignedpicks);

intmain(){usingnamespacestd;doubletotal,choices;

doublemtotal;doubleprobability1,probability2;cout<<"Entertotalnumberofgamecardchoicesand\n"

"numberofpicksallowedforthefield:\n";while((cin>>total>>choices)&&choices<=total){cout<<"Entertotalnumberofgamecardchoices""forthemeganumber:\n";if(!(cin>>mtotal))break;cout<<"Thechancesofgettingall"<<choices<<"picksisonein"<<(probability1=probability(total,choices))<<".\n";cout<<"Thechancesofgettingthemegaspotisonein"<<(probability2=probability(mtotal,1))<<".\n";cout<<"Youhaveonechancein";cout<<probability1*probability2;//computetheprobabilitycout<<"ofwinning.\n";

cout<<"Nextsetofnumbers(qtoquit):";}cout<<"bye\n";return0;}

//thefollowingfunctioncalculatestheprobabilityofpickingpicks//numberscorrectlyfromnumberschoiceslongdoubleprobability(unsignednumbers,unsignedpicks){longdoubleresult=1.0;//herecomesomelocalvariableslongdoublen;

Page 12: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 12/65

unsignedp;

for(n=numbers,p=picks;p>0;n--,p--)result=result*n/p;

returnresult;}//pe7-6.cpp#include<iostream>intFill_array(doublear[],intsize);voidShow_array(constdoublear[],intsize);voidReverse_array(doublear[],intsize);constintLIMIT=10;

intmain(){usingnamespacestd;doublevalues[LIMIT];

intentries=Fill_array(values,LIMIT);

cout<<"Arrayvalues:\n";Show_array(values,entries);cout<<"Arrayreversed:\n";Reverse_array(values,entries);Show_array(values,entries);cout<<"Allbutendvaluesreversed:\n";Reverse_array(values+1,entries-2);Show_array(values,entries);

return0;}

intFill_array(doublear[],intsize){usingnamespacestd;

intn;cout<<"Enterupto"<<size<<"values(qtoquit):\n";for(n=0;n<size;n++){cin>>ar[n];if(!cin)break;}returnn;}

voidShow_array(constdoublear[],intsize){usingnamespacestd;intn;for(n=0;n<size;n++){cout<<ar[n];if(n%8==7)cout<<endl;elsecout<<'';}if(n%8!=0)cout<<endl;}voidReverse_array(doublear[],intsize){inti,j;doubletemp;

Page 13: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 13/65

!

for(i=0,j=size-1;i<j;i++,j--){temp=ar[i];

ar[i]=ar[j];ar[j]=temp;}}

//pe7-9.cpp

#include<iostream>

doublecalculate(doublex,doubley,double(*pf)(double,double));doubleadd(doublex,doubley);doublesub(doublex,doubley);doublemean(doublex,doubley);

intmain(void)

{usingnamespacestd;double(*pf[3])(double,double)={add,sub,mean};char*op[3]={"sum","difference","mean"};doublea,b;cout<<"Enterpairsofnumbers(qtoquit):";inti;while(cin>>a>>b){//usingfunctionnamescout<<calculate(a,b,add)<<"=sum\n";cout<<calculate(a,b,mean)<<"=mean\n";//usingpointersfor(i=0;i<3;i++)cout<<calculate(a,b,pf[i])<<"="

<<op[i]<<"\n";}cout<<"Done!\n";return0;}

doublecalculate(doublex,doubley,double(*pf)(double,double)){return(*pf)(x,y);}

doubleadd(doublex,doubley){returnx+y;}

doublesub(doublex,doubley){returnx-y;}

doublemean(doublex,doubley){return(x+y)/2.0;}

Page 14: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 14/65

Page 15: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 15/65

show(testing,3);//printstestingstringthriceshow("Done!");return0;}

voidshow(constchar*str,intcnt){while(cnt-->0){cout<<str<<endl;}}

voidshow(conststringy&bny,intcnt){while(cnt-->0){

cout<<bny.str<<endl;}

}

voidset(stringy&bny,constchar*str){bny.ct=strlen(str);bny.str=newchar[bny.ct+1];strcpy(bny.str,str);}

//pe8-5.cpp#include<iostream>

template<classT>Tmax5(Tar[])

{intn;Tmax=ar[0];for(n=1;n<5;n++)if(ar[n]>max)max=ar[n];returnmax;}

constintLIMIT=5;intmain(){usingnamespacestd;doubleard[LIMIT]={-3.4,8.1,-76.4,34.4,2.4};intari[LIMIT]={2,3,8,1,9};

doublemd;intmi;

md=max5(ard);mi=max5(ari);

cout<<"md="<<md<<endl;cout<<"mi="<<mi<<endl;

return0;}

Page 16: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 16/65

//pe9-golf.h-forpe9-1.cppconstintLen=40;structgolf{charfullname[Len];inthandicap;};

//non-interactiveversion//functionsetsgolfstructuretoprovidedname,handicap//usingvaluespassedasargumentstothefunctionvoidsetgolf(golf&g,constchar*name,inthc);

//interactiveversion//functionsolicitsnameandhandicapfromuser//andsetsthemembersofgtothevaluesentered//returns1ifnameisentered,0ifnameisemptystringintsetgolf(golf&g);

//functionresetshandicaptonewvaluevoidhandicap(golf&g,inthc);

//functiondisplayscontentsofgolfstructurevoidshowgolf(constgolf&g);

//pe9-golf.cpp-forpe9-1.cpp#include<iostream>

#include"pe9-golf.h"#include<cstring>

//functionsolicitsnameandhandicapfromuser//returns1ifnameisentered,0ifnameisemptystringintsetgolf(golf&g){

std::cout<<"Pleaseentergolfer'sfullname:";std::cin.getline(g.fullname,Len);

if(g.fullname[0]=='\0')return0;//prematuretermination

std::cout<<"Pleaseenterhandicapfor"<<g.fullname<<":";while(!(std::cin>>g.handicap)){

std::cin.clear();std::cout<<"Pleaseenteraninteger:";

}while(std::cin.get()!='\n')continue;return1;}

//functionsetsgolfstructuretoprovidedname,handicapvoidsetgolf(golf&g,constchar*name,inthc){

std::strcpy(g.fullname,name);g.handicap=hc;}

//functionresetshandicaptonewvalue

Page 17: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 17/65

"

voidhandicap(golf&g,inthc){g.handicap=hc;}

//functiondisplayscontentsofgolfstructurevoidshowgolf(constgolf&g){

std::cout<<"Golfer:"<<g.fullname<<"\n";std::cout<<"Handicap:"<<g.handicap<<"\n\n";

}

//pe9-1.cpp#include<iostream>#include"pe9-golf.h"//linkwithpe9-golf.cppconstintMems=5;intmain(void)

{usingnamespacestd;golfteam[Mems];

cout<<"Enterupto"<<Mems<<"golfteammembers:\n";inti;for(i=0;i<Mems;i++)if(setgolf(team[i])==0)

break;for(intj=0;j<i;j++)showgolf(team[j]);setgolf(team[0],"FredNorman",5);showgolf(team[0]);handicap(team[0],3);showgolf(team[0]);

return0;}

//pe9-3.cpp--usingplacementnew#include<iostream>#include<new>#include<cstring>structchaff{chardross[20];intslag;

};

//charbuffer[500];//option1intmain(){usingstd::cout;usingstd::endl;chaff*p1;inti;char*buffer=newchar[500];//option2p1=new(buffer)chaff[2];//placestructuresinbufferstd::strcpy(p1[0].dross,"HorseFeathers");p1[0].slag=13;std::strcpy(p1[1].dross,"Piffle");p1[1].slag=-39;

Page 18: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 18/65

#

for(i=0;i<2;i++)cout<<p1[i].dross<<":"<<p1[i].slag<<endl;delete[]buffer;//option2

return0;}

//pe10-1.cpp#include<iostream>#include<cstring>

//classdeclaration

classBankAccount{ private:charname[40];characctnum[25];doublebalance; public:BankAccount(char*client="noone",char*num="0",doublebal=0.0);voidshow(void)const;voiddeposit(doublecash);voidwithdraw(doublecash);};

//methoddefinitionsBankAccount::BankAccount(char*client,char*num,doublebal){

std::strncpy(name,client,39);name[39]='\0';

std::strncpy(acctnum,num,24);acctnum[24]='\0';balance=bal;}

voidBankAccount::show(void)const{usingstd::cout;usingstd::endl;cout<<"Client:"<<name<<endl;cout<<"AccountNumber:"<<acctnum<<endl;cout<<"Balance:"<<balance<<endl;}

voidBankAccount::deposit(doublecash){if(cash>=0)balance+=cash;else

std::cout<<"Illegaltransactionattempted";}

voidBankAccount::withdraw(doublecash){if(cash<0)

std::cout<<"Illegaltransactionattempted";elseif(cash<=balance)balance-=cash;

Page 19: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 19/65

Page 20: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 20/65

//pe10-4a.cpp#include<iostream>#include"pe10-4.h"

intmain(){

usingSALES::Sales;

doublevals[3]={2000,3000,5000};SalesforFiji(vals,3);forFiji.showSales();

Salesred;red.showSales();red.setSales();red.showSales();

return0;}

//pe10-4b.cpp#include<iostream>#include"pe10-4.h"

namespaceSALES{usingstd::cin;usingstd::cout;usingstd::endl;

Sales::Sales(constdoublear[],intn){

if(n<0)n=0;

intlimit=n<QUARTERS?n:QUARTERS;doubletotal=0; min=0; max=0;average=0;if(limit>0)

 min=max=ar[0];inti;for(i=0;i<limit;i++){

sales[i]=ar[i];total+=ar[i];if(ar[i]>max)max=ar[i];elseif(ar[i]<min)min=ar[i];

}for(i=limit;i<QUARTERS;i++)sales[i]=0;if(limit>0)

average=total/limit;}

Sales::Sales(){

 min=0; max=0;average=0;for(inti=0;i<QUARTERS;i++)

Page 21: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 21/65

Page 22: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 22/65

Page 23: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 23/65

!

if(c!='A'&&c!='P'){

cout<<"PleaserespondwithA,P,orQ:";continue;

}switch(c){case'A':if(st.isfull())cout<<"stackalreadyfull\n";else

{get_customer(temp);st.push(temp);}break;case'P':if(st.isempty())

cout<<"stackalreadyempty\n";else{st.pop(temp);

payments+=temp.payment;cout<<temp.fullname<<"processed.";cout<<"Paymentsnowtotal$"<<payments<<"\n";}break;default:cout<<"Whoops!Programmingerror!\n";}cout<<"PleaseenterAtoaddacustomer,\n"<<"Ptoprocessacustomer,andQtoquit.\n";}cout<<"Done!\n";return0;}

voidget_customer(customer&cu){usingnamespacestd;cout<<"Entercustomername:";cin.getline(cu.fullname,35);cout<<"Entercustomerpayment:";cin>>cu.payment;while(cin.get()!='\n')continue;}

//pe10-8arr.h--headerfileforasimplelistclass

#ifndefSIMPLEST_#defineSIMPLEST_

//program-specificdeclarationsconstintTSIZE=45;//sizeofarraytoholdtitlestructfilm {chartitle[TSIZE];intrating;};

//generaltypedefinitionstypedefstructfilmItem;

Page 24: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 24/65

constintMAXLIST=10;classsimplist{ private:

Itemitems[MAXLIST];intcount; public:simplist(void);boolisempty(void);boolisfull(void);intitemcount();booladditem(Itemitem);voidtransverse(void(*pfun)(Itemitem));};

#endif

//pe10-8arr.cpp--functionssupportingsimplelistoperations

#include"pe10-8arr.h"

simplist::simplist(void){count=0;}

 boolsimplist::isempty(void){returncount==0;}

 boolsimplist::isfull(void){returncount==MAXLIST;

}

intsimplist::itemcount(){returncount;} boolsimplist::additem(Itemitem){if(count==MAXLIST)returnfalse;elseitems[count++]=item;returntrue;}

voidsimplist::transverse(void(*pfun)(Itemitem)){for(inti=0;i<count;i++)(*pfun)(items[i]);}

//pe10-8.cpp--usingaclassdefinition

#include<iostream>#include<cstdlib>//prototypeforexit()#include"pe10-8arr.h"//simplelistclassdeclaration//arrayversionvoidshowmovies(Itemitem);//tobeusedbytransverse()

Page 25: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 25/65

intmain(void){usingnamespacestd;simplistmovies;//createsanemptylist

Itemtemp;

if(movies.isfull())//invokesisfull()memberfunction{cout<<"Nomoreroominlist!Bye!\n";exit(1);}cout<<"Enterfirstmovietitle:\n";while(cin.getline(temp.title,TSIZE)&&temp.title[0]!='\0'){cout<<"Enteryourrating<0-10>:";cin>>temp.rating;while(cin.get()!='\n')continue;if(movies.additem(temp)==false)

{cout<<"Listalreadyisfull!\n";break;}if(movies.isfull()){cout<<"Youhavefilledthelist.\n";

break;}cout<<"Enternextmovietitle(emptylinetostop):\n";}if(movies.isempty())cout<<"Nodataentered.";else{

cout<<"Hereisthemovielist:\n";movies.transverse(showmovies);}

cout<<"Bye!\n";return0;}

voidshowmovies(Itemitem){

std::cout<<"Movie:"<<item.title<<"Rating:"<<item.rating<<std::endl;}

PE11-2

//pe11-2.h--Vectorclasswith<<,modestate//modifiedimplementation#ifndefMODVECTOR_H_#defineMODVECTOR_H_#include<iostream>namespaceVECTOR {usingstd::ostream;classVector{

Page 26: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 26/65

private:doublex;//horizontalvaluedoubley;//verticalvalue

charmode;//'r'=rectangular,'p'=polar

//privatemethodsforsettingvaluesvoidset_mag();voidset_ang();voidset_x(double,double);voidset_y(double,double);public:Vector();Vector(doublen1,doublen2,charform='r');voidset(doublen1,doublen2,charform='r');~Vector();doublexval()const{returnx;}//reportxvaluedoubleyval()const{returny;}//reportyvalue

doublemagval()const;//reportmagnitudedoubleangval()const;//reportanglevoidpolar_mode();//setmodeto'p'

voidrect_mode();//setmodeto'r'//operatoroverloadingVectoroperator+(constVector&b)const;Vectoroperator-(constVector&b)const;Vectoroperator-()const;Vectoroperator*(doublen)const;//friendsfriendVectoroperator*(doublen,constVector&a);friendostream&operator<<(ostream&os,constVector&v);};

}//endnamespaceVECTOR #endif

//pe11-2.cpp--modifiedmethodsforVectorclass

#include<cmath>#include"pe11-2.h"//includes<iostream>usingstd::sqrt;usingstd::sin;usingstd::cos;usingstd::atan2;usingstd::cout;

namespaceVECTOR {

constdoubleRad_to_deg=57.2957795130823;

//privatemethods//calculatesmagnitudefromxandy

//setxfrompolarcoordinatevoidVector::set_x(doublemag,doubleang){x=mag*cos(ang);}

//setyfrompolarcoordinatevoidVector::set_y(doublemag,doubleang){y=mag*sin(ang);}

//publicmethods

Page 27: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 27/65

"

Vector::Vector()//defaultconstructor{x=y=0.0;mode='r';

}

//constructvectorfromrectangularcoordinatesifformisr//(thedefault)orelsefrompolarcoordinatesifformispVector::Vector(doublen1,doublen2,charform)

{mode=form;if(form=='r'){x=n1;y=n2;}elseif(form=='p'){set_x(n1,n2/Rad_to_deg);

set_y(n1,n2/Rad_to_deg);}else{cout<<"Incorrect3rdargumenttoVector()--";cout<<"vectorsetto0\n";x=y=0.0;mode='r';}}

//setvectorfromrectangularcoordinatesifformisr(the//default)orelsefrompolarcoordinatesifformispvoidVector::set(doublen1,doublen2,charform){

mode=form;if(form=='r'){x=n1;y=n2;}elseif(form=='p')

{set_x(n1,n2/Rad_to_deg);set_y(n1,n2/Rad_to_deg);}else{cout<<"Incorrect3rdargumenttoVector()--";cout<<"vectorsetto0\n";x=y=0.0;

mode='r';}}

Vector::~Vector()//destructor{}

doubleVector::magval()const//reportmagnitude{

returnsqrt(x*x+y*y);}

doubleVector::angval()const//reportangle

Page 28: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 28/65

#

{if(x==0.0&&y==0.0)return0;else

returnatan2(y,x);}

voidVector::polar_mode()//settopolarmode{mode='p';}

voidVector::rect_mode()//settorectangularmode{mode='r';}

//operatoroverloading//addtwoVectors

VectorVector::operator+(constVector&b)const{returnVector(x+b.x,y+b.y);}

//subtractVectorbfromaVectorVector::operator-(constVector&b)const{returnVector(x-b.x,y-b.y);}

//reversesignofVectorVectorVector::operator-()const{returnVector(-x,-y);

}

//multiplevectorbynVectorVector::operator*(doublen)const{returnVector(n*x,n*y);}

//friendmethods//multiplynbyVectoraVectoroperator*(doublen,constVector&a){returna*n;}

//displayrectangularcoordinatesifmodeisr,//elsedisplaypolarcoordinatesifmodeisp

ostream&operator<<(ostream&os,constVector&v){if(v.mode=='r')os<<"(x,y)=("<<v.x<<","<<v.y<<")";elseif(v.mode=='p'){os<<"(m,a)=("<<v.magval()<<","<<v.angval()*Rad_to_deg<<")";}elseos<<"Vectorobjectmodeisinvalid";returnos;}

Page 29: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 29/65

$

}//endnamespaceVECTOR 

//pe11-2walk.cpp--usethemodifiedVectorclass

//compilewiththevect.cppfile#include<iostream>#include<cstdlib>//rand(),srand()prototypes#include<ctime>//time()prototype#include"pe11-2.h"

intmain(){usingnamespacestd;usingVECTOR::Vector;

srand(time(0));//seedrandom-numbergeneratordoubledirection;Vectorstep;Vectorresult(0.0,0.0);unsignedlongsteps=0;

doubletarget;doubledstep;cout<<"Entertargetdistance(qtoquit):";while(cin>>target){cout<<"Entersteplength:";if(!(cin>>dstep))break;

while(result.magval()<target){direction=rand()%360;step.set(dstep,direction,'p');result=result+step;steps++;

}cout<<"After"<<steps<<"steps,thesubject""hasthefollowinglocation:\n";cout<<result<<endl;result.polar_mode();cout<<"or\n"<<result<<endl;

cout<<"Averageoutwarddistanceperstep="<<result.magval()/steps<<endl;steps=0;result.set(0.0,0.0);cout<<"Entertargetdistance(qtoquit):";}cout<<"Bye!\n";

return0;}

//pe11ston.h--definitionforStonewtclass(forpe11-5)#ifndefPE11STONEWT_H_#definePE11STONEWT_H_#include<iostream>classStonewt{ private:enum{Lbs_per_stn=14};//poundsperstoneintstone;//wholestonesdoublepds_left;//fractionalpounds

Page 30: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 30/65

!

doublepounds;//entireweightinpoundscharmode;//displaymodeforweight//'s'=stone,'f'=float,'w'=wholepounds public:

Stonewt(doublelbs);//constructorfordoublepoundsStonewt(intstn,doublelbs);//constructorforstone,lbsStonewt();//defaultconstructor~Stonewt();voidset_mode(charm){mode=m;}Stonewtoperator+(constStonewt&sw)const;Stonewtoperator-(constStonewt&sw)const;Stonewtoperator*(doublem)const;friendStonewtoperator*(doublem,constStonewt&sw){returnsw*m;}friendstd::ostream&operator<<(std::ostream&os,constStonewt&sw);};#endif

//pe11ston.h--definitionforStonewtclass(forpe11-5)

#ifndefPE11STONEWT_H_#definePE11STONEWT_H_#include<iostream>classStonewt{ private:enum{Lbs_per_stn=14};//poundsperstoneintstone;//wholestonesdoublepds_left;//fractionalpoundsdoublepounds;//entireweightinpoundscharmode;//displaymodeforweight//'s'=stone,'f'=float,'w'=wholepounds public:Stonewt(doublelbs);//constructorfordoublepoundsStonewt(intstn,doublelbs);//constructorforstone,lbs

Stonewt();//defaultconstructor~Stonewt();voidset_mode(charm){mode=m;}Stonewtoperator+(constStonewt&sw)const;Stonewtoperator-(constStonewt&sw)const;Stonewtoperator*(doublem)const;friendStonewtoperator*(doublem,constStonewt&sw){returnsw*m;}friendstd::ostream&operator<<(std::ostream&os,constStonewt&sw);};#endif

//pe11-5.cpp#include<iostream>#include"pe11ston.h"//linkwithpe11ston.cppintmain(void){usingstd::cout;Stonewtfullback(245.5);Stonewtcornerback(13,5.2);cout<<fullback;cout<<cornerback;cornerback.set_mode('w');cout<<cornerback;Stonewtlump;lump=fullback+cornerback;cout<<lump;fullback=fullback*1.1;cout<<fullback;

Page 31: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 31/65

!

lump=lump-fullback;cout<<lump;lump=1.3*lump;lump.set_mode('s');

cout<<lump;

return0;}

//pe11-7.cpp#include<iostream>#include"complex0.h"//toavoidconfusionwithcomplex.hintmain(){usingstd::cout;

usingstd::endl;usingstd::cin;

complexa(3.0,4.0);//initializeto(3,4i)complexc;cout<<"Enteracomplexnumber(qtoquit):\n";while(cin>>c){cout<<"cis"<<c<<endl;cout<<"complexconjugateis"<<~c<<endl;cout<<"ais"<<a<<endl;cout<<"a+cis"<<a+c<<endl;cout<<"a-cis"<<a-c<<endl;cout<<"a*cis"<<a*c<<endl;cout<<"2*cis"<<2*c<<endl;cout<<"Enteracomplexnumber(qtoquit):\n";}cout<<"Done!\n";return0;}

//complex0.h#ifndefCOMPLEX0_H_#defineCOMPLEX0_H_#include<iostream>

classcomplex{ private:doubler;doublei;

 public:complex();complex(doublereal);complex(doublereal,doubleimag);doublemagnitude();complexoperator+(constcomplex&z)const;complexoperator-(constcomplex&z)const;complexoperator~()const;friendcomplexsquare(constcomplex&z);friendcomplexoperator*(constcomplex&z,constcomplex&w);friendstd::ostream&operator<<(std::ostream&os,constcomplex&z);friendstd::istream&operator>>(std::istream&is,complex&z);};#endif

Page 32: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 32/65

!

//complex0.cpp#include<iostream>#include<cmath>#include"complex0.h"

complex::complex(){r=i=0.0;}

complex::complex(doublereal){r=real;i=0.0;}

complex::complex(doublereal,doubleimag){r=real;

i=imag;}

doublecomplex::magnitude(){returnstd::sqrt(r*r+i*i);}complexcomplex::operator+(constcomplex&z)const{complexsum;sum.r=r+z.r;sum.i=i+z.i;returnsum;}

complexcomplex::operator-(constcomplex&z)const{complexsum;sum.r=r+z.r;sum.i=i+z.i;returnsum;}

complexcomplex::operator~()const{complexconjugate;conjugate.r=r;conjugate.i=-i;returnconjugate;}complexsquare(constcomplex&z){complexsq;sq.r=z.r*z.r-z.i*z.i;sq.i=2.0*z.r*z.i;returnsq;}

complexoperator*(constcomplex&z,constcomplex&w){complexsq;sq.r=w.r*z.r-w.i*z.i;

sq.i=w.r*z.i+w.i*z.r;returnsq;}

Page 33: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 33/65

!!

std::ostream&operator<<(std::ostream&os,constcomplex&z){

os<<'('<<z.r<<','<<z.i<<"i)";returnos;}

std::istream&operator>>(std::istream&is,complex&z){std::cout<<"real:";if(is>>z.r){std::cout<<"imaginary:";is>>z.i;}returnis;}

//pe12-2.cpp#include<iostream>//#include"string2.h"#include"pe12strg.h"//alternativenameintmain(){usingstd::cout;usingstd::cin;Strings1("andIamaC++student.");Strings2="Pleaseenteryourname:";Strings3;cout<<s2;//overloaded<<operatorcin>>s3;//overloaded>>operator

s2="Mynameis"+s3;//overloaded=,+operatorscout<<s2<<".\n";s2=s2+s1;s2.stringup();//convertsstringtouppercasecout<<"Thestring\n"<<s2<<"\ncontains"<<s2.has('A')<<"'A'charactersinit.\n";s1="red";//String(constchar*),//thenString&operator=(constString&)Stringrgb[3]={String(s1),String("green"),String("blue")};cout<<"Enterthenameofaprimarycolorformixinglight:";Stringans;

boolsuccess=false;while(cin>>ans){ans.stringlow();//convertsstringtolowercasefor(inti=0;i<3;i++){if(ans==rgb[i])//overloaded==operator

{cout<<"That'sright!\n";success=true;break;}}if(success)

Page 34: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 34/65

!

break;elsecout<<"Tryagain!\n";}

cout<<"Bye\n";return0;}

//pe12strg.h

#ifndefPE12STRG_H_#definePE12STRG_H_#include<iostream>

classString{ private:char*str;//pointertoastringintchars;//numberofcharactersstaticintstrings;//totalnumberofstrings

 public:String();String(constchar*ps);//convertsC++stringtoStringString(constString&s);~String();intnumstrings();intlen();voidstringup();voidstringlow();inthas(charch);String&operator=(constString&s);friendstd::ostream&operator<<(std::ostream&os,constString&s);friendstd::istream&operator>>(std::istream&os,String&s);friendStringoperator+(constString&s1,constString&s2);friendintoperator==(constString&s1,constString&s2);

friendintoperator<(constString&s1,constString&s2);friendintoperator>(constString&s1,constString&s2);};

#endif//pe12strg.cpp#include<iostream>#include<cctype>//#include"string2.h"#include"pe12strg.h"//alternativenameintString::strings=0;

String::String(){str=NULL;chars=0;strings++;}

String::String(constchar*ps){chars=std::strlen(ps);str=newchar[chars+1];std::strcpy(str,ps);

strings++;}

String::String(constString&s){chars=s.chars;

Page 35: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 35/65

!

str=newchar[chars+1];std::strcpy(str,s.str);strings++;}

String::~String(){strings--;delete[]str;}

intString::numstrings(){returnstrings;}

intString::len(){returnchars;

}

voidString::stringup(){for(inti=0;i<chars;i++)str[i]=std::toupper(str[i]);}

voidString::stringlow(){for(inti=0;i<chars;i++)str[i]=std::tolower(str[i]);}

String&String::operator=(constString&s)//allowschaining

{if(this==&s)//assignmenttoselfreturn*this;delete[]str;//freeoldcontents,ifanychars=s.chars;str=newchar[chars+1];std::strcpy(str,s.str);return*this;}

std::ostream&operator<<(std::ostream&os,constString&s){os<<s.str;returnos;}

std::istream&operator>>(std::istream&is,String&s){chartemp[80];is.getline(temp,80);s=temp;returnis;}

Stringoperator+(constString&s1,constString&s2){intlen=s1.chars+s2.chars;char*ps=newchar[len+1];std::strcpy(ps,s1.str);std::strcat(ps,s2.str);

Page 36: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 36/65

!

Stringtemp(ps);returntemp;}

intString::has(charch){intct=0;char*ps=str;while(*ps){if(*ps++==ch)++ct;}returnct;}

intoperator==(constString&s1,constString&s2){if(s1.chars!=s2.chars)

return0;elseif(std::strcmp(s1.str,s2.str)==0)return1;elsereturn0;}

intoperator<(constString&s1,constString&s2){if(std::strcmp(s1.str,s2.str)<0)return1;elsereturn0;}intoperator>(constString&s1,constString&s2)

{if(std::strcmp(s1.str,s2.str)>0)return1;elsereturn0;}

//pe12stak.h--classdefinitionforthestackADT#ifndefPE12STAK_H_#definePE12STAK_H_

typedefunsignedlongItem;

classStack{ private:enum{MAX=10};//constantspecifictoclassItem*pitems;//holdsstackitemsintsize;//maxnumberofelementsinstackinttop;//indexfortopstackitem Stack(constStack&st){}//nocopyingofstacksStack&operator=(constStack&st){return*this;}//noassignment public:Stack(intn=MAX);~Stack();boolisempty()const;boolisfull()const;

Page 37: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 37/65

!"

//push()returnsfalseifstackalreadyisfull,trueotherwiseboolpush(constItem&item);//additemtostack//pop()returnsfalseifstackalreadyisempty,trueotherwiseboolpop(Item&item);//poptopintoitem 

};#endif

//pe12stak.cpp--Stackmemberfunctions#include"pe12stak.h"Stack::Stack(intn)//createanemptystack{size=n;pitems=newItem[size];top=0;}Stack::~Stack(){delete[]pitems;}

 boolStack::isempty()const{

returntop==0?true:false;}

 boolStack::isfull()const{returntop==size?true:false;}

 boolStack::push(constItem&item){if(top<size){pitems[top++]=item;returntrue;}

elsereturnfalse;}

 boolStack::pop(Item&item){if(top>0){item=pitems[--top];returntrue;}elsereturnfalse;}

//pe12-4.cpp

#include<iostream>#include<cctype>#include"pe12stak.h"//modifiedtodefinecustomerstructure//linkwithpe12stak.cppintmain(void){usingnamespacestd;

Stackst(3);//createastackofponumbersunsignedlongtemp;charc;

cout<<"PleaseenterAtoaddaPO,\n"<<"PtoprocessaPO,andQtoquit.\n";

Page 38: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 38/65

!#

while(cin>>c&&(c=toupper(c))!='Q'){while(cin.get()!='\n')continue;

if(c!='A'&&c!='P'){cout<<"PleaserespondwithA,P,orQ:";continue;}switch(c){case'A':if(st.isfull())cout<<"stackalreadyfull\n";else{cout<<"EnterPOnumber:";cin>>temp;st.push(temp);}

break;case'P':if(st.isempty())cout<<"stackalreadyempty\n";else{st.pop(temp);cout<<"ProcessingPO"<<temp<<'\n';}break;default:cout<<"Whoops!Programmingerror!\n";}cout<<"PleaseenterAtoaddacustomer,\n"<<"Ptoprocessacustomer,andQtoquit.\n";}cout<<"Done!\n";return0;

}

//pe12que.h--interfaceforaqueue#ifndef_QUEUE_H_#define_QUEUE_H_//ThisqueuewillcontainCustomeritemsclassCustomer{ private:longarrive;//arrivaltimeforcustomerintprocesstime;//processingtimeforcustomer public:

Customer(){arrive=processtime=0;}voidset(longwhen);longwhen()const{returnarrive;}intptime()const{returnprocesstime;}};

typedefCustomerItem;

classQueue{ private://classscopedefinitions//NodeisanestedstructuredefinitionlocaltothisclassstructNode{Itemitem;structNode*next;};enum{Q_SIZE=10};

Page 39: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 39/65

!$

//privateclassmembersNode*front;//pointertofrontofQueueNode*rear;//pointertorearofQueueintitems;//currentnumberofitemsinQueue

constintqsize;//maximumnumberofitemsinQueue//preemptivedefinitionstopreventpubliccopyingQueue(constQueue&q):qsize(0){}Queue&operator=(constQueue&q){return*this;} public:Queue(intqs=Q_SIZE);//createqueuewithaqslimit~Queue();boolisempty()const;boolisfull()const;intqueuecount()const;boolenqueue(constItem&item);//additemtoendbooldequeue(Item&item);//removeitemfromfront};#endif

//pe12que.cpp--QueueandCustomermethods#include"pe12que.h"#include<cstdlib>//(orstdlib.h)forrand()usingstd::rand;

//QueuemethodsQueue::Queue(intqs):qsize(qs){front=rear=NULL;items=0;}

Queue::~Queue(){Node*temp;

while(front!=NULL)//whilequeueisnotyetempty{temp=front;//saveaddressoffrontitem front=front->next;//resetpointertonextitem deletetemp;//deleteformerfront}}

 boolQueue::isempty()const{returnitems==0;}

 boolQueue::isfull()const{returnitems==qsize;}

intQueue::queuecount()const{returnitems;}

//Additemtoqueue boolQueue::enqueue(constItem&item){if(isfull())returnfalse;Node*add=newNode;//createnodeif(add==NULL)

Page 40: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 40/65

returnfalse;//quitifnoneavailableadd->item=item;//setnodepointersadd->next=NULL;items++;

if(front==NULL)//ifqueueisempty,front=add;//placeitematfrontelserear->next=add;//elseplaceatrearrear=add;//haverearpointtonewnodereturntrue;}

//Placefrontitemintoitemvariableandremovefromqueue boolQueue::dequeue(Item&item){if(front==NULL)returnfalse;item=front->item;//setitemtofirstiteminqueueitems--;

Node*temp=front;//savelocationoffirstitem front=front->next;//resetfronttonextitem deletetemp;//deleteformerfirstitem if(items==0)rear=NULL;returntrue;}

//customermethod

//whenisthetimeatwhichthecustomerarrives//thearrivaltimeissettowhenandtheprocessing//timesettoarandomvalueintherange1-3voidCustomer::set(longwhen){

processtime=std::rand()%3+1;arrive=when;}

//pe12-6.cpp--usetheQueueinterface//linktope12que.cpp//modifyListing12.10byaddingasecondqueue#include<iostream>#include<ctime>//fortime()#include<cstdlib>//forrand()andsrand()#include"pe12que.h"

constlongMIN_PER_HR=60L;

 boolnewcustomer(doublex);//isthereanewcustomer?

intmain(void){usingstd::cin;

usingstd::cout;usingstd::endl;usingstd::ios_base;

//settingthingsupstd::srand(std::time(0));//randominitializingofrand()

cout<<"CaseStudy:BankofHeatherAutomaticTeller\n";cout<<"Entermaximumsizeofeachqueue:";intqs;cin>>qs;

Page 41: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 41/65

Queueline1(qs);//linequeueholdsuptoqspeopleQueueline2(qs);//secondqueue

cout<<"Enterthenumberofsimulationhours:";

inthours;//hoursofsimulationcin>>hours;//simulationwillrun1cycleperminutelongcyclelimit=MIN_PER_HR*hours;//#ofcyclesItemtemp;//newcustomerdatalongturnaways;//turnedawaybyfullqueuelongcustomers;//joinedthequeuelongserved;//servedduringthesimulationlongsum_line;//cumulativelinelengthintwait_time1;//timeuntilautoteller1isfreeintwait_time2;//timeuntilautoteller2isfreelongline_wait;//cumulativetimeinlinedoublemin_per_cust;//averagetimebetweenarrivals

cout<<"Entertheaveragenumberofcustomersperhour:";

doubleperhour;//average#ofarrivalperhourcin>>perhour;while(perhour>0)//beginnewloop{min_per_cust=MIN_PER_HR/perhour;turnaways=0;customers=0;served=0;sum_line=0;wait_time1=wait_time2=0;line_wait=0;

//runningthesimulationfor(longcycle=0;cycle<cyclelimit;cycle++){

if(newcustomer(min_per_cust))//havenewcomer{if(line1.isfull()&&line2.isfull())turnaways++;else//atleastonelineisnotfull{customers++;temp.set(cycle);//cycle=timeofarrival//addcustomertoshorterlineif(line1.queuecount()<=line2.queuecount())line1.enqueue(temp);//addnewcomertoline1elseline2.enqueue(temp);//addnewcomertoline2}}//processcustomersinfirstqueueif(wait_time1<=0&&!line1.isempty()){line1.dequeue(temp);//attendnextcustomerwait_time1=temp.ptime();//forwait_timeminutesline_wait+=cycle-temp.when();served++;}if(wait_time1>0)wait_time1--;sum_line+=line1.queuecount();//processcustomersinsecondqueueif(wait_time2<=0&&!line2.isempty()){line2.dequeue(temp);//attendnextcustomer

Page 42: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 42/65

wait_time2=temp.ptime();//forwait_timeminutesline_wait+=cycle-temp.when();

served++;}

if(wait_time2>0)wait_time2--;sum_line+=line2.queuecount();}//reportingresultsif(customers>0){cout<<"customersaccepted:"<<customers<<'\n';cout<<"customersserved:"<<served<<'\n';cout<<"turnaways:"<<turnaways<<'\n';cout<<"averagequeuesize:";cout.precision(2);cout.setf(ios_base::fixed,ios_base::floatfield);cout.setf(ios_base::showpoint);cout<<(double)sum_line/cyclelimit<<'\n';

cout<<"averagewaittime:"<<(double)line_wait/served<<"minutes\n";}elsecout<<"Nocustomers!\n";//clearqueueswhile(!line1.isempty())line1.dequeue(temp);while(!line2.isempty())line2.dequeue(temp);

cout<<"Enternewvalueforcustomersperhour(0toquit):";cin>>perhour;}//endofnewloopcout<<"Bye\n";

return0;}

//x=averagetime,inminutes,betweencustomers//returnvalueistrueifcustomershowsupthisminute boolnewcustomer(doublex){if(std::rand()*x/RAND_MAX<1)returntrue;else

returnfalse;

}

//cd.h--baseclass

#ifndefCD_H_#defineCD_H_

classCd{//representsaCDdisk private:charperformers[50];charlabel[20];intselections;//numberofselections

Page 43: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 43/65

!

doubleplaytime;//playingtimeinminutes public:Cd(constchar*s1,constchar*s2,intn,doublex);//Cd(constCd&d);//defaultversionisfine

Cd();virtual~Cd(){}virtualvoidReport()const;//reportsallCDdata//Cd&operator=(constCd&d);//defaultversionisfine};

#endif

//pe13-1cd.cpp--cdmethods#include<iostream>#include<cstring>#include"cd.h"

Cd::Cd(constchar*s1,constchar*s2,intn,doublex){

std::strncpy(performers,s1,49);performers[49]='\0';std::strncpy(label,s2,19);label[19]='\0';selections=n;playtime=x;}

Cd::Cd(){performers[0]='\0';label[0]='\0';selections=0;playtime=0.0;}

voidCd::Report()const{usingstd::cout;usingstd::endl;cout<<"Performer(s):"<<performers<<endl;cout<<"Label:"<<label<<endl;cout<<"Numberofselections:"<<selections<<endl;cout<<"Playtime:"<<playtime<<endl;}

//classic.h//derivedclass

#ifndefCLASSIC_H_#defineCLASSIC_H_

#include"cd.h"

classClassic:publicCd{ private:charprimarywork[50]; public:Classic(constchar*pw,constchar*s1,constchar*s2,intn,doublex);Classic();voidReport()const;//redefinetoreportprimarywork};

Page 44: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 44/65

#endif

//pe13-1cl.cpp

//Classicmethods#include<iostream>#include<cstring>#include"classic.h"

Classic::Classic(constchar*pw,constchar*s1,constchar*s2,intn,doublex):Cd(s1,s2,n,x){std::strncpy(primarywork,pw,49);primarywork[49]='\0';}Classic::Classic():Cd(){primarywork[0]='\0';

}voidClassic::Report()const{std::cout<<"Primarywork:"<<primarywork<<std::endl;

Cd::Report();}

//pe13-1.cpp

#include<iostream>usingnamespacestd;#include"classic.h"//whichwillcontain#includecd.hvoidBravo(constCd&disk);intmain(){

Cdc1("Beatles","Capitol",14,35.5);Classicc2=Classic("PianoSonatainBflat,FantasiainC","AlfredBrendel","Philips",2,57.17);Cd*pcd=&c1;

cout<<"Usingobjectdirectly:\n";c1.Report();//useCdmethodc2.Report();//useClassicmethod

cout<<"Usingtypecd*pointertoobjects:\n";pcd->Report();//useCdmethodforcdobjectpcd=&c2;pcd->Report();//useClassicmethodforclassicobject

cout<<"CallingafunctionwithaCdreferenceargument:\n";Bravo(c1);Bravo(c2);

cout<<"Testingassignment:";Classiccopy;copy=c2;copy.Report();

return0;}

voidBravo(constCd&disk){disk.Report();}

Foxit Reader ±à¼°æȨËùÓÐ (C) Foxit Software Company,2005-2006½öÓÃÓÚÆÀ¹À¡£

Page 45: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 45/65

//pe13dma.h--inheritanceanddynamicmemoryallocation

#ifndefDMA_H_#defineDMA_H_#include<iostream>

//AbstractBaseClassclassABC{ private:char*label;intrating; public:ABC(constchar*l="null",intr=0);ABC(constABC&rs);virtual~ABC()=0;

virtualABC&operator*(){return*this;}ABC&operator=(constABC&rs);virtualvoidView()const;friendstd::ostream&operator<<(std::ostream&os,constABC&rs);};

//FormerBaseClassUsingDMA classbaseDMA:publicABC{ private:

 public:baseDMA(constchar*l="null",intr=0);};

//derivedclasswithoutDMA //nodestructorneeded//usesimplicitcopyconstructor//usesimplicitassignmentoperatorclasslacksDMA:publicABC{ private:charcolor[40]; public:lacksDMA(constchar*c="blank",constchar*l="null",intr=0);lacksDMA(constchar*c,constABC&rs);voidView()const;

};

//derivedclasswithDMA classhasDMA:publicABC{ private:char*style; public:hasDMA(constchar*s="none",constchar*l="null",intr=0);hasDMA(constchar*s,constABC&rs);hasDMA(consthasDMA&hs);~hasDMA();hasDMA&operator=(consthasDMA&rs);

Page 46: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 46/65

voidView()const;};

#endif

//pe13dma.cpp--dmaclassmethods

#include"pe13dma.h"#include<cstring>

//ABCmethods ABC::ABC(constchar*l,intr){label=newchar[std::strlen(l)+1];std::strcpy(label,l);rating=r;}

 ABC::ABC(constABC&rs)

{label=newchar[std::strlen(rs.label)+1];std::strcpy(label,rs.label);rating=rs.rating;}

 ABC::~ABC(){delete[]label;}

 ABC&ABC::operator=(constABC&rs){if(this==&rs)return*this;

delete[]label;label=newchar[std::strlen(rs.label)+1];std::strcpy(label,rs.label);rating=rs.rating;return*this;}

voidABC::View()const{std::cout<<"Label:"<<label<<std::endl;std::cout<<"Rating:"<<rating<<std::endl;}

std::ostream&operator<<(std::ostream&os,constABC&rs){rs.View();returnos;}

//baseDMAmethods baseDMA::baseDMA(constchar*l,intr):ABC(l,r){}

//lacksDMAmethodslacksDMA::lacksDMA(constchar*c,constchar*l,intr):ABC(l,r){std::strncpy(color,c,39);

Page 47: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 47/65

"

color[39]='\0';}

lacksDMA::lacksDMA(constchar*c,constABC&rs)

:ABC(rs){std::strncpy(color,c,39);color[39]='\0';}

voidlacksDMA::View()const{ABC::View();std::cout<<"Color:"<<color<<std::endl;}

//hasDMAmethodshasDMA::hasDMA(constchar*s,constchar*l,intr)

:ABC(l,r){style=newchar[std::strlen(s)+1];std::strcpy(style,s);}

hasDMA::hasDMA(constchar*s,constABC&rs):ABC(rs){style=newchar[std::strlen(s)+1];std::strcpy(style,s);}

hasDMA::hasDMA(consthasDMA&hs):ABC(hs)//invokebaseclasscopyconstructor

{style=newchar[std::strlen(hs.style)+1];std::strcpy(style,hs.style);}

hasDMA::~hasDMA(){delete[]style;}

hasDMA&hasDMA::operator=(consthasDMA&hs){if(this==&hs)return*this;ABC::operator=(hs);//copybaseportionstyle=newchar[std::strlen(hs.style)+1];std::strcpy(style,hs.style);return*this;}

voidhasDMA::View()const{

ABC::View();std::cout<<"Style:"<<style<<std::endl;}

//pe13-3.cpp--inheritance,friends,andDMA //compilewithpe13dma.cpp#include<iostream>#include"pe13dma.h"

Page 48: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 48/65

#

intmain(){usingstd::cout;usingstd::endl;

baseDMAshirt("Portabelly",8);lacksDMAballoon("red","Blimpo",4);hasDMAmap("Mercator","BuffaloKeys",5);cout<<shirt<<endl;cout<<balloon<<endl;cout<<map<<endl;lacksDMAballoon2(balloon);hasDMAmap2;map2=map;

cout<<balloon2<<endl;cout<<map2<<endl;

ABC*pts[3];pts[0]=&shirt;pts[1]=&balloon;

pts[2]=&map;

for(inti=0;i<3;i++)cout<<*pts[i]<<endl;for(inti=0;i<3;i++)pts[i]->View();return0;}

//pairs.h--defineaPairtemplate

#ifndefPAIRS_H_#definePAIRS_H_

template<classT1,classT2>classPair{ private:T1a;T2b; public:T1&first();T2&second();T1first()const{returna;}T2second()const{returnb;}Pair(constT1&aval,constT2&bval):a(aval),b(bval){}

Pair(){}};

#endif

//winec.h--wineclassusingcontainment#ifndefWINEC_H_#defineWINEC_H_

#include<iostream>#include<string>#include<valarray>#include"pairs.h"

classWine

Page 49: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 49/65

$

{ private:typedefstd::valarray<int>ArrayInt;

typedefPair<ArrayInt,ArrayInt>PairArray;

std::stringlabel;//winebrandnameintyears;//numberofyearsPairArraydata;

 public:Wine():label("none"),years(0),data(ArrayInt(),ArrayInt()){}Wine(constchar*l,inty,constintyr[],constintbot[]);Wine(constchar*l,constArrayInt&yr,constArrayInt&bot);Wine(constchar*l,constPairArray&yr_bot);Wine(constchar*l,inty);voidGetBottles();voidShow()const;

conststd::string&Label(){returnlabel;}intsum()const{returndata.second().sum();}

};

#endif

//winec.cpp--Wineclasswithcontainment#include<iostream>#include"winec.h"

usingstd::cin;usingstd::cout;usingstd::cerr;usingstd::endl;

 Wine::Wine(constchar*l,inty,constintyr[],constintbot[]):label(l),years(y),data(ArrayInt(yr,y),ArrayInt(bot,y)){

}

 Wine::Wine(constchar*l,constArrayInt&yr,constArrayInt&bot):label(l),years(yr.size()),data(ArrayInt(yr),ArrayInt(yr)){if(yr.size()!=bot.size()){cerr<<"Yeardata,bottledatamismatch,arraysetto0size.\n";years=0;

data=PairArray(ArrayInt(),ArrayInt());}else{data.first()=yr;data.second()=bot;}}

 Wine::Wine(constchar*l,constPairArray&yr_bot):label(l),years(yr_bot.first().size()),data(yr_bot){}

 Wine::Wine(constchar*l,inty):label(l),years(y),data(ArrayInt(0,y),ArrayInt(0,y)){}

voidWine::GetBottles(){if(years<1){cout<<"Nospaceallocatedfordata\n";

Page 50: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 50/65

return;}

cout<<"Enter"<<label<<

"datafor"<<years<<"year(s):\n";for(inti=0;i<years;i++){cout<<"Enteryear:";cin>>data.first()[i];cout<<"Enterbottlesforthatyear:";cin>>data.second()[i];}}

voidWine::Show()const{cout<<"Wine:"<<label<<endl;cout<<"\tYear\tBottles\n";for(inti=0;i<years;i++)

cout<<'\t'<<data.first()[i]<<'\t'<<data.second()[i]<<endl;}

//pe14-1.cpp--usingWineclasswithcontainment

#include<iostream>#include"winec.h"

intmain(void){usingstd::cin;usingstd::cout;usingstd::endl;

cout<<"Enternameofwine:";charlab[50];cin.getline(lab,50);cout<<"Enternumberofyears:";intyrs;cin>>yrs;

Wineholding(lab,yrs);//storelabel,years,givearraysyrselementsholding.GetBottles();//solicitinputforyear,bottlecountholding.Show();//displayobjectcontents

constintYRS=3;inty[YRS]={1993,1995,1998};intb[YRS]={48,60,72};//createnewobject,initializeusingdatainarraysyandbWinemore("GushingGrapeRed",YRS,y,b);more.Show();cout<<"Totalbottlesfor"<<more.Label()//useLabel()method<<":"<<more.sum()<<endl;//usesum()methodcout<<"Bye\n";return0;}

PE14- 2

//pairs.h--defineaPairtemplate#ifndefPAIRS_H_#definePAIRS_H_

template<classT1,classT2>

Page 51: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 51/65

Page 52: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 52/65

 Wine::Wine(constchar*l,constArrayInt&yr,constArrayInt&bot):string(l),years(yr.size()),PairArray(ArrayInt(yr),ArrayInt(yr)){

if(yr.size()!=bot.size()){cerr<<"Yeardata,bottledatamismatch,arraysetto0size.\n";years=0;PairArray::operator=(PairArray(ArrayInt(),ArrayInt()));}else{PairArray::first()=yr;PairArray::second()=bot;}}

 Wine::Wine(constchar*l,constPairArray&yr_bot):string(l),years(yr_bot.first().size()),PairArray(yr_bot){}

 Wine::Wine(constchar*l,inty):string(l),years(y),PairArray(ArrayInt(0,y),ArrayInt(0,y)){}

voidWine::GetBottles(){if(years<1){cout<<"Nospaceallocatedfordata\n";return;}

cout<<"Enter"<<Label()<<

"datafor"<<years<<"year(s):\n";for(inti=0;i<years;i++){cout<<"Enteryear:";cin>>PairArray::first()[i];cout<<"Enterbottlesforthatyear:";cin>>PairArray::second()[i];}}

voidWine::Show()const{cout<<"Wine:"<<Label()<<endl;cout<<"\tYear\tBottles\n";for(inti=0;i<years;i++)cout<<'\t'<<PairArray::first()[i]<<'\t'<<PairArray::second()[i]<<endl;}

//pe14-2.cpp--usingWineclasswithprivateinheritance#include<iostream>#include"winei.h"

intmain(void){usingstd::cin;usingstd::cout;usingstd::endl;

Page 53: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 53/65

!

cout<<"Enternameofwine:";charlab[50];cin.getline(lab,50);cout<<"Enternumberofyears:";

intyrs;cin>>yrs;

Wineholding(lab,yrs);//storelabel,years,givearraysyrselementsholding.GetBottles();//solicitinputforyear,bottlecountholding.Show();//displayobjectcontents

constintYRS=3;inty[YRS]={1993,1995,1998};intb[YRS]={48,60,72};//createnewobject,initializeusingdatainarraysyandbWinemore("GushingGrapeRed",YRS,y,b);more.Show();cout<<"Totalbottlesfor"<<more.Label()//useLabel()method<<":"<<more.sum()<<endl;//usesum()method

cout<<"Bye\n";return0;}

//pe14-pg.h

#include<iostream>#include<cstring>#include<cstdlib>

constintLen=20;classPerson

{ private:charfname[Len];charlname[Len]; public:Person(){fname[0]=lname[0]='\0';}Person(constchar*fn,constchar*ln);virtual~Person(){}virtualvoidshow()const{std::cout<<fname<<""<<lname;}virtualvoidset();};

classGunslinger:virtualpublicPerson{ private:

doubledrawtime;intnotches; public:Gunslinger():Person("Joe","Doe"),drawtime(0.0),notches(0){}Gunslinger(constchar*fn,constchar*ln,doubled=1.0,intn=0):Person(fn,ln),drawtime(d),notches(n){}Gunslinger(constPerson&p,doubled=1.0,intn=0):Person(p),drawtime(d),notches(n){}virtual~Gunslinger(){}//Person(p)isthedefaultcopyconstructordoubledraw(){returndrawtime;}voidshow()const;voidset();

Page 54: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 54/65

};

classPokerPlayer:virtualpublicPerson{

 public:PokerPlayer():Person("Busted","Strait"){}PokerPlayer(constchar*fn,constchar*ln):Person(fn,ln){}PokerPlayer(constPerson&p):Person(p){}virtual~PokerPlayer(){}intdraw()const{returnstd::rand()%52+1;}};

classBadDude:publicGunslinger,publicPokerPlayer{ public:

BadDude():Person("Bad","Dude"),Gunslinger(){}BadDude(constchar*fn,constchar*ln,doubled=1.0,intn=0):Person(fn,ln),Gunslinger(fn,ln,d,n){}

BadDude(constPerson&p,doubled=1.0,intn=0):Person(p),Gunslinger(p,d,n){}doublegdraw()const{returnGunslinger::draw();}intcdraw()const{returnPokerPlayer::draw();}voidshow()const{Gunslinger::show();}voidset(){Gunslinger::set();}};

#include<iostream>#include<cstring>#include"pe14-4pg.h"

Person::Person(constchar*fn,constchar*ln){std::strncpy(fname,fn,Len-1);

fname[Len-1]='\0';std::strncpy(lname,ln,Len-1);lname[Len-1]='\0';}

voidPerson::set(){std::cout<<"Enterfirstname:";std::cin.getline(fname,Len);std::cout<<"Enterlastname:";std::cin.getline(lname,Len);}voidGunslinger::set(){Person::set();std::cout<<"Enterdrawtime:";std::cin>>drawtime;std::cout<<"Enternumberofnotches:";std::cin>>notches;}

voidGunslinger::show()const{Person::show();std::cout<<":"<<drawtime<<"drawtime,"<<notches<<"notches\n";}

//pe14-4.cpp

Page 55: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 55/65

#include<iostream>#include<cstring>#include"pe14-4pg.h"constintSIZE=5;

intmain(void){usingnamespacestd;intct,i;Person*gang[SIZE];for(ct=0;ct<SIZE;ct++){charchoice;cout<<"Enterthegangcategory:\n"<<"o:ordinarypersong:gunslinger"<<"p:pokerplayerb:baddudeq:quit\n";cin>>choice;while(strchr("ogpbq",choice)==NULL){cout<<"Pleaseenterano,g,p,b,orq:";

cin>>choice;}if(choice=='q')break;switch(choice){case'o':gang[ct]=newPerson;break;case'g':gang[ct]=newGunslinger;

break;case'p':gang[ct]=newPokerPlayer;break;case'b':gang[ct]=newBadDude;break;}

cin.get();gang[ct]->set();}

cout<<"\nHereisyourgang:\n";for(i=0;i<ct;i++){cout<<'\n';gang[i]->show();}for(i=0;i<ct;i++)deletegang[i];cout<<"\nBye!\n";return0;}

//pe15tv.h--TvandRemoteclasses

#ifndefPE15TV_H_#definePE15TV_H_

classTv{ public:friendclassRemote;//RemotecanaccessTvprivateparts

Page 56: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 56/65

enumState{Off,On};enum{MinVal,MaxVal=20};enum{Antenna,Cable};enum{TV,VCR};

Tv(States=Off,intmc=100):state(s),volume(5),maxchannel(mc),channel(2),mode(Cable),input(TV){}voidonoff(){state=(state==On)?Off:On;}boolison(){returnstate==On?true:false;}boolvolup();boolvoldown();voidchanup();voidchandown();voidset_mode(){mode=(mode==Antenna)?Cable:Antenna;}voidset_input(){input=(input==TV)?VCR:TV;}voidsettings();voidrmode(Remote&r); private:Statestate;

intvolume;intmaxchannel;intchannel;intmode;intinput;};

classRemote{friendclassTv;

 public:enumStyle{Normal,Interactive};Remote(intm=Tv::TV,ints=Normal):mode(m),style(s){}

boolvolup(Tv&t){returnt.volup();}boolvoldown(Tv&t){returnt.voldown();}voidonoff(Tv&t){t.onoff();}voidchanup(Tv&t){t.chanup();}voidchandown(Tv&t){t.chandown();}voidset_chan(Tv&t,intc){t.channel=c;}voidset_mode(Tv&t){t.set_mode();}voidset_input(Tv&t){t.set_input();}voidshow_style(); private:intmode;//TVorVCR intstyle;//NormalorInteractive};

//placedefinitionherewherebothTvandRemote//classdeclarationsareknowninlinevoidTv::rmode(Remote&r){if(state==Off)return;if(r.style==Remote::Normal)r.style=Remote::Interactive;elser.style=Remote::Normal;}#endif

//pe15tv.cpp

#include<iostream>#include"pe15tv.h"

Page 57: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 57/65

"

 boolTv::volup(){

if(volume<MaxVal)

{volume++;returntrue;}elsereturnfalse;} boolTv::voldown(){if(volume>MinVal){volume--;returntrue;}else

returnfalse;}

voidTv::chanup(){if(channel<maxchannel)channel++;elsechannel=1;}

voidTv::chandown(){if(channel>1)channel--;

elsechannel=maxchannel;}

voidTv::settings(){usingstd::cout;cout<<"TVis"<<(state==Off?"Off\n":"On\n");if(state==On){cout<<"Volumesetting="<<volume<<"\n";cout<<"Channelsetting="<<channel<<"\n";cout<<"Mode="<<(mode==Antenna?"antenna\n":"cable\n");cout<<"Input="<<(input==TV?"TV\n":"VCR\n");}}

voidRemote::show_style(){if(style==Normal)std::cout<<"RemoteinNormalmode\n";elsestd::cout<<"RemoteinInteractivemode\n";}

//pe15-1.cpp//linkwithpe15tv.cpp

Page 58: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 58/65

#

#include<iostream>#include"pe15tv.h"

intmain(void)

{Tvs20;std::cout<<"Initialsettingsfor20\"TV:\n";s20.settings();s20.onoff();s20.chanup();std::cout<<"\nAdjustedsettingsfor20\"TV:\n";s20.settings();

Remotegrey;

grey.set_chan(s20,10);grey.volup(s20);grey.volup(s20);std::cout<<"\n20\"settingsafterusingremote\n";

s20.settings();

Tvs27(Tv::On);s27.set_mode();grey.set_chan(s27,28);std::cout<<"\n27\"settings:\n";s27.settings();grey.show_style();//checkmodes27.rmode(grey);//changemodegrey.show_style();//recheckmodes27.onoff();//turnsetoffs27.rmode(grey);//trychangingmodeagaingrey.show_style();//checkresult

return0;

}

//pe15-2.h--exceptionclassesforhmean(),gmean()#ifndefPE15_2_H_#definePE15_2_H_

#include<iostream>#include<stdexcept>

classhmeanexcp:publicstd::logic_error{ public:hmeanexcp():std::logic_error("hmean()invalidarguments:a=-b\n")

{

}};

classgmeanexcp:publicstd::logic_error{ public:gmeanexcp():std::logic_error("gmean()argumentsshouldbe>=0\n"){

}};#endif

Page 59: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 59/65

$

//pe15-2.cpp#include<iostream>

#include<cmath>//ormath.h,unixusersmayneed-lmflag#include"pe15-2.h"//functionprototypesdoublehmean(doublea,doubleb)throw(hmeanexcp);doublegmean(doublea,doubleb)throw(gmeanexcp);intmain(){usingstd::cout;usingstd::cin;usingstd::endl;

doublex,y,z;

cout<<"Entertwonumbers:";while(cin>>x>>y)

{try{//startoftryblockz=hmean(x,y);cout<<"Harmonicmeanof"<<x<<"and"<<y<<"is"<<z<<endl;cout<<"Geometricmeanof"<<x<<"and"<<y<<"is"<<gmean(x,y)<<endl;cout<<"Enternextsetofnumbers<qtoquit>:";}//endoftryblockcatch(hmeanexcp&bg)//startofcatchblock{cout<<bg.what();cout<<"Tryagain.\n";continue;}

catch(gmeanexcp&bh){cout<<bh.what();cout<<"Sorry,youdon'tgettoplayanymore.\n";break;}//endofcatchblock}cout<<"Bye!\n";return0;}

doublehmean(doublea,doubleb)throw(hmeanexcp){if(a==-b)throwhmeanexcp();return2.0*a*b/(a+b);}

doublegmean(doublea,doubleb)throw(gmeanexcp){if(a<0||b<0)throwgmeanexcp();returnstd::sqrt(a*b);}

Page 60: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 60/65

//pe16-1.cpp--oneofmanypossiblesolutions#include<iostream>#include<string>

 boolisPal(conststd::string&s);

intmain(){std::stringinput;

std::cout<<"Enterastring(emptystringtoquit):\n";std::getline(std::cin,input);

while(std::cin&&input.size()>0){if(isPal(input))std::cout<<"Thatwasapalindrome!\n";elsestd::cout<<"Thatwasnotapalindrome!\n";

std::cout<<"Enterastring(emptystringtoquit):\n";std::getline(std::cin,input);}std::cout<<"Bye!\n";

return0;}

 boolisPal(conststd::string&s){std::stringrev(s.rbegin(),s.rend());//constructreversedstring

//someoldercompilersdon’timplementtheaboveconstructor//anotherapproachisthis//std::stringrev(s);//revsamesizeass

//copy(s.rbegin(),s.rend(),rev.begin());

return(rev==s);}

//pe16-4.cpp--onepossibility

#include<iostream>#include<algorithm>#defineMAX10

intreduce(longar[],intn);voidshow(constlongar[],intn);

intmain(){longmyarray[MAX]={12,12,5,6,11,5,6,77,11,12};

show(myarray,MAX);

intnewsize=reduce(myarray,MAX);show(myarray,newsize);return(0);}

Page 61: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 61/65

intreduce(longar[],intn){//oronecouldcopytoalistanduselistmethods//orcopytoaset;ineithercase,copyresults

//backtoarraystd::sort(ar,ar+n);long*past_end;past_end=std::unique(ar,ar+n);returnpast_end-ar;}

voidshow(constlongar[],intn){for(inti=0;i<n;i++)std::cout<<ar[i]<<'';std::cout<<std::endl;}

//pe16-8.cpp

#include<iostream>#include<set>#include<algorithm>#include<iterator>#include<cstdlib>#include<string>

intmain(){usingnamespacestd;stringtemp;

set<string>mats;cout<<"EnterMat'sguestlist(emptylinetoquit):\n";while(getline(cin,temp)&&temp.size()>0)mats.insert(temp);ostream_iterator<string,char>out(cout,"\n");cout<<"Mat'sguestlist:\n";copy(mats.begin(),mats.end(),out);

set<string>pats;cout<<"EnterPat'sguestlist(emptylinetoquit):\n";while(getline(cin,temp)&&temp.size()>0)pats.insert(temp);cout<<"\nPat'sguestlist:\n";copy(pats.begin(),pats.end(),out);

set<string>both;set_union(mats.begin(),mats.end(),pats.begin(),pats.end(),insert_iterator<set<string>>(both,both.begin()));cout<<"\nMergedguestlist:\n";copy(both.begin(),both.end(),out);

return0;}

Page 62: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 62/65

//pe17-1.cpp#include<iostream>

intmain(void){usingnamespacestd;charch;intcount=0;

while(cin.get(ch)&&ch!='$')count++;if(ch=='$')cin.putback(ch);elsecout<<"Endofinputwasreached\n";cout<<count<<"charactersread\n";cin.get(ch);cout<<"Thennextinputcharacteris"<<ch<<endl;

return0;}

//pe17-3.cpp#include<iostream>#include<fstream>#include<cstdlib>

intmain(intargc,char*argv[]){usingnamespacestd;if(argc<3)

{cerr<<"Usage:"<<argv[0]<<"source-filetarget-file\n";exit(EXIT_FAILURE);}ifstreamfin(argv[1]);if(!fin){cerr<<"Can'topen"<<argv[1]<<"forinput\n";exit(EXIT_FAILURE);}ofstreamfout(argv[2]);if(!fout){cerr<<"Can'topen"<<argv[2]<<"foroutput\n";exit(EXIT_FAILURE);}charch;while(fin.get(ch))fout<<ch;cout<<"Contentsof"<<argv[1]<<"copiedto"<<argv[2]<<endl;fin.close();fout.close();

return0;}

Page 63: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 63/65

!

//pe17-5.cpp#include<iostream>#include<fstream>#include<set>

#include<algorithm>#include<iterator>#include<cstdlib>#include<string>

intmain(){usingnamespacestd;ifstreammat("mat.dat");if(!mat.is_open()){cerr<<"Can'topenmat.dat.\n";exit(1);}ifstreampat("pat.dat");

if(!pat.is_open()){cerr<<"Can'topenpat.dat.\n";exit(1);}

ofstreammatnpat("matnpat.dat");if(!matnpat.is_open()){cerr<<"Can'topenpat.dat.\n";exit(1);}

stringtemp;

set<string>mats;while(getline(mat,temp))mats.insert(temp);ostream_iterator<string,char>out(cout,"\n");cout<<"Mat'sguestlist:\n";copy(mats.begin(),mats.end(),out);

set<string>pats;while(getline(pat,temp))pats.insert(temp);cout<<"\nPat'sguestlist:\n";copy(pats.begin(),pats.end(),out);

ostream_iterator<string,char>fout(matnpat,"\n");set<string>both;set_union(mats.begin(),mats.end(),pats.begin(),pats.end(),insert_iterator<set<string>>(both,both.begin()));cout<<"\nMergedguestlist:\n";copy(both.begin(),both.end(),out);copy(both.begin(),both.end(),fout);

return0;}if(!pat.is_open()){cerr<<"Can'topenpat.dat.\n";exit(1);}

ofstreammatnpat("matnpat.dat");

Page 64: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 64/65

if(!matnpat.is_open()){cerr<<"Can'topenpat.dat.\n";

exit(1);

}

stringtemp;

set<string>mats;while(getline(mat,temp))mats.insert(temp);ostream_iterator<string,char>out(cout,"\n");cout<<"Mat'sguestlist:\n";copy(mats.begin(),mats.end(),out);

set<string>pats;while(getline(pat,temp))pats.insert(temp);cout<<"\nPat'sguestlist:\n";

copy(pats.begin(),pats.end(),out);

ostream_iterator<string,char>fout(matnpat,"\n");set<string>both;set_union(mats.begin(),mats.end(),pats.begin(),pats.end(),insert_iterator<set<string>>(both,both.begin()));cout<<"\nMergedguestlist:\n";copy(both.begin(),both.end(),out);copy(both.begin(),both.end(),fout);

return0;

}

//pe17-7.cpp#include<iostream>#include<fstream>#include<string>#include<vector>#include<algorithm>#include<cstdlib>

voidShowStr(conststd::string&s);voidGetStrs(std::istream&is,std::vector<std::string>&vs);

classStore{

 public:std::ostream&os;Store(std::ostream&o):os(o){}voidoperator()(conststd::string&s);};

intmain(){usingnamespacestd;vector<string>vostr;stringtemp;

//acquirestringscout<<"Enterstrings(emptylinetoquit):\n";

while(getline(cin,temp)&&temp[0]!='\0')

Page 65: C++Primer Plus 5thEdition编程练习答案【非扫描】

8/3/2019 C++Primer Plus 5thEdition

http://slidepdf.com/reader/full/cprimer-plus-5thedition 65/65

vostr.push_back(temp);cout<<"Hereisyourinput.\n";for_each(vostr.begin(),vostr.end(),ShowStr);

//storeinafileofstreamfout("strings.dat",ios_base::out|ios_base::binary);

for_each(vostr.begin(),vostr.end(),Store(fout));fout.close();

//recoverfilecontentsvector<string>vistr;ifstreamfin("strings.dat",ios_base::in|ios_base::binary);if(!fin.is_open()){cerr<<"Couldnotopenfileforinput.\n";exit(EXIT_FAILURE);}GetStrs(fin,vistr);cout<<"\nHerearethestringsreadfromthefile:\n";

for_each(vistr.begin(),vistr.end(),ShowStr);

return0;}

voidShowStr(conststd::string&s){std::cout<<s<<std::endl;}

voidStore::operator()(conststd::string&s){std::size_tlen=s.size();os.write((char*)&len,sizeof(std::size_t));os.write(s.data(),len);

}

voidGetStrs(std::istream&is,std::vector<std::string>&vs){std::stringtemp;size_tlen;

while(is.read((char*)&len,sizeof(size_t))&&len>0){charch;temp="";for(intj=0;j<len;j++){if(is.read(&ch,1)){temp+=ch;}elsebreak;}if(is)vs.push_back(temp);}}