C++Primer源代码Word格式.docx
《C++Primer源代码Word格式.docx》由会员分享,可在线阅读,更多相关《C++Primer源代码Word格式.docx(105页珍藏版)》请在冰豆网上搜索。
feet\n"
return0;
}
3.WriteaC++programthatusesthreeuser-definedfunctions(countingmain()asone)andproducesthefollowingoutput:
Threeblindmice
Seehowtheyrun
Onefunction,calledtwotimes,shouldproducethefirsttwolines,andtheremainingfunction,alsocalledtwice,shouldproducetheremainingoutput.
//pe2-3.cpp
voidmice();
voidrun();
intmain()
mice();
run();
voidmice()
Threeblindmice\n"
voidrun()
Seehowtheyrun\n"
4.Writeaprogramthathasmain()callauser-definedfunctionthattakesaCelsiustemperaturevalueasanargumentandthenreturnstheequivalentFahrenheit
StephenPrata1July22,1999SampleSolutionsforProgrammingExercisesinC++PrimerPlus,3rdEdition
value.TheprogramshouldrequesttheCelsiusvalueasinputfromtheuseranddisplaytheresult,asshowninthefollowingcode:
PleaseenteraCelsiusvalue:
20
20degreesCelsiusis68degreesFahrenheit.
Forreference,hereistheformulaformakingtheconversion:
Fahrenheit=1.8×
Celsius+32.0
//pe2-4.cpp
doubleC_to_F(double);
EnteratemperatureinCelsius:
doubleC;
C;
doubleF;
F=C_to_F(C);
C<
degreesCelsius="
F<
degreesFahrenheit\n"
doubleC_to_F(doubletemp)
return1.8*temp+32.0;
Chapter3
1.Writeashortprogramthatasksforyourheightinintegerinchesandthenconvertsyourheighttofeetandinches.Havetheprogramusetheunderlinecharactertoindicatewheretotypetheresponse.Alsouseaconsttype.
//pe3-1.cpp
constintInch_Per_Foot=12;
//Note:
someenvironmentsdon'
tsupportthebackspacecharacter
Pleaseenteryourheightininches:
___/b/b/b"
intht_inch;
ht_inch;
intht_feet=ht_inch/Inch_Per_Foot;
intrm_inch=ht_inch%Inch_Per_Foot;
Yourheightis"
<
ht_feet<
feet,"
rm_inch<
inch(es).\n"
3.Writeaprogramthataskshowmanymilesyouhavedrivenandhowmanygallonsofgasolineyouusedandthenreportsthemilespergallonyourcargot.Or,
StephenPrata2July22,1999SampleSolutionsforProgrammingExercisesinC++PrimerPlus,3rdEdition
ifyouprefer,theprogramcanrequestdistanceinkilometersandpetrolinlitersandthenreporttheresultEuropeanstyle,inlitersper100kilometers.(Or,perhaps,youcanuselitresper100kilometres.)
//pe3-3.cpp
Howmanymileshaveyoudrivenyourcar?
floatmiles;
miles;
Howmanygallonsofgasolinedidthecaruse?
floatgallons;
gallons;
Yourcargot"
miles/gallons;
milespergallon.\n"
Chapter4
2.TheCandyBarstructurecontainsthreemembers.Thefirstmemberholdsthebrandnameofacandybar.Thesecondmemberholdstheweight(whichmayhaveafractionalpart)ofthecandybar,andthethirdmemberholdsthenumberofcalories(anintegervalue)inthecandybar.WriteaprogramthatdeclaressuchastructureandcreatesaCandyBarvariablecalledsnack,initializingitsmembersto"
MochaMunch"
2.3,and350respectively.Theinitializationshouldbepartofthedeclarationforsnack.Finally,theprogramshoulddisplaythecontentsofthesnackvariable.
//pe4-2.cpp//acandybarstructCandyBar{charbrand[40];
doubleweight;
intcalories;
};
#include<
usingnamespacestd;
//introducesnamespacestd
CandyBarsnack={"
2.3,350};
Brandname:
snack.brand<
endl;
Weight:
snack.weight<
Calories:
snack.calories<
StephenPrata3July22,1999SampleSolutionsforProgrammingExercisesinC++PrimerPlus,3rdEdition
4.WilliamWingaterunsapizza-analysisservice.Foreachpizza,heneedstorecordthefollowinginformation:
[lb]thenameofthepizzacompany,whichmayconsistofmorethanoneword
[lb]thediameterofpizza
[lb]theweightofthepizza
Deviseastructurethatcanholdthisinformationandwriteaprogramusingastructurevariableofthattype.Theprogramshouldasktheusertoentereachoftheitemsofinformationlistedabove,andthentheprogramshoulddisplaythatinformation.Usecin(oritsmethods)andcout.
//pe4-4.ccp
constintSlen=70;
structpizza{
charname[Slen];
floatdiameter;
floatweight;
};
pizzapie;
Whatisthenameofthepizzacompany?
cin.getline(pie.name,Slen);
Whatisthediameterofthepizzaininches?
pie.diameter;
Howmuchdoesthepizzaweighinounces?
pie.weight;
Company:
pie.name<
\n"
Diameter:
pie.diameter<
inches\n"
pie.weight<
ounces\n"
Chapter5
2.Writeaprogramthatasksyoutotypeinnumbers.Aftereachentry,thenumberreportsthecumulativesumoftheentriestodate.Theprogramterminateswhenyouenterazero.
//pe5-2.cpp
doublesum=0.0;
doublein;
Enteranumber(0toterminate):
in;
while(in!
=0){
sum+=in;
Runningtotal="
sum<
StephenPrata4July22,1999SampleSolutionsforProgrammingExercisesinC++PrimerPlus,3rdEdition
Enternextnumber(0toterminate):
Bye!
4.YousellC++ForFools.Writeaprogramthathasyouenterayear'
sworthofmonthlysales(intermsofnumberofbooks,notofmoney).Theprogramshouldusealooptopromptyoubymonth,usinganarrayofchar*initializedtothemonthstringsandstoringtheinputdatainanarrayofint.Then,theprogramshouldfindthesumofthearraycontentsandreportthetotalsalesfortheyear.
//pe5-4.cpp//booksales#include<
constintMONTHS=12;
constchar*months[MONTHS]={"
January"
"
February"
March"
April"
"
May"
June"
July"
August"
September"
October"
November"
December"
intsales[MONTHS];
intmonth;
Enterthemonthlysalesfor\"
C++forFools\"
:
for(month=0;
month<
MONTHS;
month++)
Salesfor"
months[month]<
sales[month];
doubletotal=0.0;
total+=sales[month];
Totalsales:
total<
6.Designastructurecalledcarthatholdsthefollowinginformationaboutanautomobile:
itsmake(asastringinacharacterarray)andtheyearitwasbuilt(asaninteger).Writeaprogramthataskstheuserhowmanycarstocatalog.Theprogramshouldthenusenewtocreateadynamicarrayofthatmanycarstructures.Next,itshouldprompttheusertoinputthemakeandyearinformationforeachstructure.Notethatthisrequiressomecare,foritalternatesreadingstringswithnumericdata.(SeeChapter4,"
DerivedTypes,"
formoreinformation.)Finally,itshoulddisplaythecontentsofeachstructure.Asamplerunshouldlooksomethinglikethefollowing:
Howmanycarsdoyouwishtocatalog?
2
Car#1:
Pleaseenterthemake:
HudsonHornet
Pleaseentertheyearmade:
1952
Car#2:
StephenPrata5July22,1999SampleSolutionsforProgrammingExercisesinC++PrimerPlus,3rdEdition
Kaiser
1951
Hereisyourcollection:
1952HudsonHornet
1951Kaiser
//pe5-6.cpp
structcar{charname[20];
intyear;
intn;
n;
while(cin.get()!
='
\n'
)//getridofrestofline
car*pc=newcar[n];
inti;
for(i=0;
i<
i++)
Car#"
(i+1)<
cin.getline(pc[i].name,20);
pc[i].year;
pc[i].year<
pc[i].name<
delete[]pc;
7.Writeaprogramusingnestedloopsthataskstheusertoenteravalueforthenumberofrowstodisplayed.Itthendisplaysthatmanyrowsofasterisks,withoneasteriskinthefirstrow,twointhesecondrow,andsoon.Foreachrow,theasterisksareprecededbythenumberofperiodsneededtomakealltherowsdisplayatotalnumberofcharactersequaltothenumberofrows.Asamplerunwouldlooklikethis:
Enternumberofrows:
5
....*
...**
..***
.****
*****
//pe5-7.cpp
//nestedloops
introws;
introw;
intcol;
StephenPrata6July22,1999SampleSolutionsforProgr