版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
.
/
Instructor’sManual
for
C++HowtoProgram,3/e
Deitel,Deitel&Nieto
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
C++HowtoProgram:ThirdEdition
Instructor’sManualContents
Prefaceiii
Chapter1IntroductiontoComputersandC++Programming:Solutions1
Chapter2ControlStructures:Solutions15
Chapter3Functions:Solutions66
Chapter4ArraysSolutions:120
Chapter5PointersandStrings:Solutions170
Chapter6ClassesandDataAbstraction:Solutions235
Chapter7Classes:PartII:Solutions264
Chapter8OperatorOverloading:Solutions276
Chapter9Inheritance:Solutions299
Chapter10VirtualFunctionsandPolymorphism:Solutions318
Chapter11C++StreamInput/Output:Solutions333
Chapter12Templates:Solutions348
Chapter13ExceptionHandling:Solutions359
Chapter14FileProcessing:Solutions370
Chapter15DataStructures:Solutions390
Chapter16Bits,Characters,StringsandStructures:Solutions498
Chapter17ThePreprocessor:Solutions524
Chapter18CLegacyCodeTopics:Solutions531
Chapter19ClassstringandStringStreamProcessing:Solutions541
Chapter20StandardTemplateLibrary<STL>:Solutions559
Chapter21StandardC++LanguageAdditions:Solutions565
AppendixC++MultimediaCyberClassroomSolutionsProvidedonCD573
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
Preface
Thankyouforconsideringand/oradoptingourtextC++HowtoProgram:ThirdEdition.Ifyouhavenotread
theprefacetoC++HowtoProgram:ThirdEdition,pleasedoso.Theprefacecontainsacarefulwalkthroughof
thebook’skeyfeatures,includingournewUnifiedModelingLanguage.<UML.>casestudy,whichcarefully
introducesthereadertotheUMLandobject-orienteddesign<OOD>.Studentsarepresentedwithadetailedproblem
statementandguidedthroughasimplified,UML-basedobject-orienteddesignprocess.Thecomplete1000line
C++programsolutionforthecasestudyispresentedinthebookandprovidedontheCD-ROMintheback
ofthetextbook.
Wehaveworkedhardtoproduceatextbookandancillariesthatwehopeyouandyourstudentswillfindvaluable.
Thefollowingancillaryresourcesareavailable:
.
C++HowtoProgram:ThirdEdition’s250programexamplesareincludedontheCD-ROMintheback
ofthetextbook.ThishelpsinstructorspreparelecturesfasterandhelpsstudentsmasterC++.Theexamples
arealsoavailablefordownloadat.WhenextractingthesourcecodefromtheZIPfile,
youmustuseaZIP-filereadersuchasWinZip<>orPKZIP<>
thatunderstandsdirectories.Thefileshouldbeextractedintoaseparatedirectory<e.g.,
cpphtp3e_examples>.
.
MicrosoftVisualC++6IntroductoryEditionsoftwareisprovidedonthetextbook’sCD-ROM.Thissoftware
allowsstudentstoedit,compileanddebugC++programs.WehaveprovidedatnochargeashortVisual
C++6tutorial<inAdobePDFformat>onourWebsite<>.
.ThisC++HowtoProgram:ThirdEditionInstructor’sManualonCDcontainsanswerstomostoftheexercises
inthetextbook.Theprogramsareseparatedintodirectoriesbychapterandexercisenumber.
.TheoptionalC++MultimediaCyberClassroom:ThirdEditionisaninteractivemultimediaCDversionof
thebookforWindows.Itsfeaturesincludeaudiowalkthroughsofprograms,sectionreviewquestions<which
areavailableonlyontheC++MultimediaCyberClassroom:ThirdEdition>,atext-searchengine,theability
toexecuteexampleprograms,andmore.TheCyberClassroomhelpsstudentsgetmoreoutoftheircourses.
TheCyberClassroomisalsousefulforstudentswhomissalectureandhavetocatchupquickly.TheCyber
Classroomisavailableasastand-aloneproduct<seethelastfewpagesofthetextbookfortheISBNnumber>
orbundledwiththetextbook<atadiscount>inaproductcalledTheCompleteC++TrainingCourse:Third
Edition<ISBN#0-13-089563-6>.
.
CompanionWebsite</deitel>providesinstructorandstudentresources.Instructor
resourcesincludetextbookappendices<e.g.,AppendixD,"C++InternetandWebResources">and
asyllabusmanagerforlessonplanning.Studentresourcesincludechapterobjectives,true/falsequestions,
chapterhighlights,referencematerialsandamessageboard.
.CustomizablePowerpointInstructorLectureNotes,withmanycompletefeaturesincludingsourcecode,
andkeydiscussionpointsforeachprogramandmajorillustration.Theselecturenotesareavailableforinstructors
andstudentsatnochargeatourWebsite.
.LabManual<availableSpring2001>—afor-saleitemcontainingclosed-labsessions.
Wewouldsincerelyappreciateyourquestions,comments,criticismsandcorrectionsaddressedtousat:
deitel@
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
Wewillrespondimmediately.PleasereadthelatestcopyoftheDeitelBuzz<publishedeveryApriland
November>forinformationonforthcomingDeitelpublications,ancillaries,productoptionsandorderinginformation.
ToreceivetheDeitelBuzz,pleasecontactJennieBurger<jennie_burger@>.
WatchourDeitel&Associates,Inc.Website<>andourPrenticeHallWebsite
</deitel>forthelatestpublicationupdates.
WewouldliketothanktheextraordinaryteamofpublishingprofessionalsatPrenticeHallwhomadeC++
HowtoProgram:ThirdEditionanditsancillariespossible.OurComputerScienceeditor,PetraRecter,worked
closelywithustoensurethetimelyavailabilityandprofessionalqualityoftheseancillaries.
Wewouldalsoliketothanktwoofourstudentinterns—AftabBukhari<aComputerSciencemajoratBoston
University>andJasonRosenfeld<aComputerSciencemajoratNorthwesternUniversity>fortheirassistancein
preparingthisInstructor’sManual.
HarveyM.Deitel
PaulJ.Deitel
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
1
IntroductiontoComputersand
C++Programming
Solutions
SOLUTIONS
1.10
Categorizeeachofthefollowingitemsaseitherhardwareorsoftware:
a>CPU
ANS:hardware.
b>C++compiler
ANS:software.
c>ALU
ANS:hardware.
d>C++preprocessor
ANS:software.
e>inputunit
ANS:hardware.
f>aneditorprogram
ANS:software.
1.11
Whymightyouwanttowriteaprograminamachine-independentlanguageinsteadofamachine-dependentlanguage?
Whymightamachine-dependentlanguagebemoreappropriateforwritingcertaintypesofprograms?
ANS:Machineindependentlanguagesareusefulforwritingprogramstobeexecutedonmultiplecomputerplatforms.
Machinedependentlanguagesareappropriateforwritingprogramstobeexecutedonasingleplatform.Machinedependent
languagestendtoexploittheefficienciesofaparticularmachine.
1.12
Fillintheblanksineachofthefollowingstatements:
a>Whichlogicalunitofthecomputerreceivesinformationfromoutsidethecomputerforusebythecomputer?
.
ANS:inputunit.
b>Theprocessofinstructingthecomputertosolvespecificproblemsiscalled.
ANS:computerprogramming.
c>WhattypeofcomputerlanguageusesEnglish-likeabbreviationsformachinelanguageinstructions?.
ANS:high-levellanguage.
d>Whichlogicalunitofthecomputersendsinformationthathasalreadybeenprocessedbythecomputertovariousde
vicessothattheinformationmaybeusedoutsidethecomputer?.
ANS:outputunit.
e>Whichlogicalunitofthecomputerretainsinformation?.
ANS:memoryunitandsecondarystorageunit.
f>Whichlogicalunitofthecomputerperformscalculations?.
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
2IntroductiontoComputersandC++ProgrammingSolutions
Chapter1
ANS:arithmeticandlogicalunit.
g>Whichlogicalunitofthecomputermakeslogicaldecisions?.
ANS:arithmeticandlogicalunit.
h>Thelevelofcomputerlanguagemostconvenienttotheprogrammerforwritingprogramsquicklyandeasilyis
.
ANS:high-levellanguage.
i>Theonlylanguagethatacomputercandirectlyunderstandiscalledthatcomputer's.
ANS:machinelanguage.
j>Whichlogicalunitofthecomputercoordinatestheactivitiesofalltheotherlogical
units?.
ANS:centralprocessingunit.
1.13
Discussthemeaningofeachofthefollowingobjects:
a>cin
ANS:Thisobjectreferstothestandardinputdevicethatisnormallyconnectedtothekeyboard.
b>cout
ANS:Thisobjectreferstothestandardoutputdevicethatisnormallyconnectedtothecomputerscreen.
c>cerr
ANS:Thisobjectreferstothestandarderrordevicethatisnormallyconnectedtothecomputerscreen.
1.14
Whyissomuchattentiontodayfocusedonobject-orientedprogrammingingeneralandC++inparticular?
ANS:Object-orientedprogrammingenablestheprogrammertobuildreusablesoftwarecomponentsthatmodelitemsin
therealworld.Buildingsoftwarequickly,correctly,andeconomicallyhasbeenanelusivegoalinthesoftwareindustry.
Themodular,object-orienteddesignandimplementationapproachhasbeenfoundtoincreaseproductivity10to100times
overconventionalprogramminglanguageswhilereducingdevelopmenttime,errors,andcost.C++isextremelypopular
becauseitisasupersetofthewidelyusedCprogramminglanguage.ProgrammersalreadyfamiliarwithChaveaneasier
timelearingC++.
1.15
Fillintheblanksineachofthefollowing:
a>areusedtodocumentaprogramandimproveitsreadability.
ANS:comments
b>Theobjectusedtoprintinformationonthescreenis.
ANS:cout
c>AC++statementthatmakesadecisionis.
ANS:if
d>Calculationsarenormallyperformedbystatements.
ANS:assignment
e>Theobjectinputsvaluesfromthekeyboard.
ANS:cin
1.16
WriteasingleC++statementorlinethataccomplisheseachofthefollowing:
a>Printthemessage"Entertwonumbers".
ANS:cout<<"Entertwonumbers";
b>Assigntheproductofvariablesbandctovariablea.
ANS:a=b*c;
c>Statethataprogramperformsasamplepayrollcalculation<i.e.,usetextthathelpstodocumentaprogram>.
ANS://SamplePayrollCalculationProgram
d>Inputthreeintegervaluesfromthekeyboardandintointegervariablesa,bandc.
ANS:cin>>a>>b>>c;
1.17
Statewhichofthefollowingaretrueandwhicharefalse.Iffalse,explainyouranswers.
a>C++operatorsareevaluatedfromlefttoright.
ANS:False.Someoperatorsareevaluatedfromlefttoright,whileotheroperatorsareevaluatedrighttoleft.
b>Thefollowingareallvalidvariablenames:_under_bar_,m928134,t5,j7,her_sales,
his_account_total,a,b,c,z,z2.
ANS:True.Allvariablesbeginwithanunderscoreorletter.
c>Thestatementcout<<"a=5;";isatypicalexampleofanassignmentstatement.
ANS:False.Thestatementisanoutputstatement.a=5;isoutputtothescreen.
d>AvalidC++arithmeticexpressionwithnoparenthesesisevaluatedfromlefttoright.
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
Chapter1
IntroductiontoComputersandC++ProgrammingSolutions3
ANS:False.Arithmeticoperatorscanappearinanyorderinanexpression.Sincemultiplication,division,andmodulus
havehigherprecendencethanadditionandsubtractionthestatementcannotbetrue.
e>Thefollowingareallinvalidvariablenames:3g,87,67h2,h22,2h.
ANS:False.h22isavalidvariablename.
1.18
Fillintheblanksineachofthefollowing:
a>Whatarithmeticoperationsareonthesamelevelofprecedenceasmultiplication?.
ANS:divisionandmodulus.
b>Whenparenthesesarenested,whichsetofparenthesesisevaluatedfirstinanarithmeticexpression?.
ANS:innermost.
c>Alocationinthecomputer'smemorythatmaycontaindifferentvaluesatvarioustimesthroughouttheexecutionofa
programiscalleda.
ANS:variable.
1.19
What,ifanything,printswheneachofthefollowingC++statementsisperformed?Ifnothingprints,thenanswer"nothing."
Assumex=2andy=3.
a>cout<<x;
ANS:2
b>cout<<x+x;
ANS:4
c>cout<<"x=";
ANS:x=
d>cout<<"x="<<x;
ANS:
x=2
e>cout<<x+y<<"="<<y+x;
ANS:5=5
f>z=x+y;
ANS:nothing.
g>cin>>x>>y;
ANS:23.
h>//cout<<"x+y="<<x+y;
ANS:nothing.
i>cout<<"\n";
ANS:Anewlineisoutputwhichpositionsthecursoratthebeginningofthenextlineonthescreen.
1.20
WhichofthefollowingC++statementscontainvariableswhosevaluesarereplaced?
a>cin>>b>>c>>d>>e>>f;
b>p=i+j+k+7;
c>cout<<"variableswhosevaluesaredestroyed";
d>cout<<"a=5";
ANS:Parts<a>and<b>.
1.21
Giventhealgebraicequationy=ax3+7,whichofthefollowing,ifany,arecorrectC++statementsforthisequation?
a>y=a*x*x*x+7;
b>y=a*x*x*<x+7>;
c>y=<a*x>*x*<x+7>;
d>y=<a*x>*x*x+7;
e>y=a*<x*x*x>+7;
f>y=a*x*<x*x+7>;
ANS:Parts<a>,<d>and<e>.
1.22
StatetheorderofevaluationoftheoperatorsineachofthefollowingC++statementsandshowthevalueofxaftereach
statementisperformed.
a>x=7+3*6/2-1;
ANS:*,/,+,-,=,15
b>x=2%2+2*2-2/2;
ANS:%,*,/,+,-,=,3
c>x=<3*9*<3+<9*3/<3>>>>;
ANS:*,/,+,*,*,324
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
4IntroductiontoComputersandC++ProgrammingSolutionsChapter1
1.23Writeaprogramthataskstheusertoentertwonumbers,obtainsthetwonumbersfromtheuserandprintsthesum,product,
difference,andquotientofthetwonumbers.
1//Exercise1.23Solution
2#include<iostream>
3
4usingstd::cout;
5usingstd::endl;
6usingstd::cin;
7
8intmain<>
9{
10intnum1,num2;//declarevariables
11
12cout<<"Entertwointegers:";//promptuser
13cin>>num1>>num2;//readvaluesfromkeyboard
14
15//outputtheresults
16cout<<"Thesumis"<<num1+num2
17<<"\nTheproductis"<<num1*num2
18<<"\nThedifferenceis"<<num1-num2
19<<"\nThequotientis"<<num1/num2<<endl;
20
21return0;//indicatesuccessfultermination
22}
Entertwointegers:822
Thesumis30
Theproductis176
Thedifferenceis-14
Thequotientis0
1.24Writeaprogramthatprintsthenumbers1to4onthesamelinewitheachpairofadjacentnumbersseparatedbyonespace.
Writetheprogramusingthefollowingmethods:
a>Usingoneoutputstatementwithonestreaminsertionoperator.
b>Usingoneoutputstatementwithfourstreaminsertionoperators.
c>Usingfouroutputstatements.
1//Exercise1.24Solution
2#include<iostream>
3
4usingstd::cout;
5usingstd::endl;
6
7intmain<>
8{
9//PartA
10cout<<"1234\n";
11
12//PartB
13cout<<"1"<<"2"<<"3"<<"4\n";
14
15//PartC
16cout<<"1";
17cout<<"2";
18cout<<"3";
19cout<<"4"<<endl;
20
21return0;
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
Chapter1IntroductiontoComputersandC++ProgrammingSolutions5
22}
1234
1234
1234
1.25Writeaprogramthataskstheusertoentertwointegers,obtainsthenumbersfromtheuser,thenprintsthelargernumber
followedbythewords"islarger."Ifthenumbersareequal,printthemessage"Thesenumbersareequal."
1//Exercise1.25Solution
2#include<iostream>
3
4usingstd::cout;
5usingstd::endl;
6usingstd::cin;
7
8intmain<>
9{
10intnum1,num2;//declaration
11
12cout<<"Entertwointegers:";//prompt
13cin>>num1>>num2;//inputtonumbers
14
15if<num1==num2>
16cout<<"Thesenumbersareequal."<<endl;
17
18if<num1>num2>
19cout<<num1<<"islarger."<<endl;
20
21if<num2>num1>
22cout<<num2<<"islarger."<<endl;
23
24return0;
25}
Entertwointegers:228
22islarger.
1.26Writeaprogramthatinputsthreeintegersfromthekeyboardandprintsthesum,average,product,smallestandlargestof
thesenumbers.Thescreendialogueshouldappearasfollows:
Inputthreedifferentintegers:132714
Sumis54
Averageis18
Productis4914
Smallestis13
Largestis27
1//Exercise1.26Solution
2#include<iostream>
3
4usingstd::cout;
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
6IntroductiontoComputersandC++ProgrammingSolutionsChapter1
5usingstd::endl;
6usingstd::cin;
7
8intmain<>
9{
10intnum1,num2,num3,smallest,largest;//declaration
11
12cout<<"Inputthreedifferentintegers:";//prompt
13cin>>num1>>num2>>num3;//input
14
15largest=num1;//assumefirstnumberislargest
16
17if<num2>largest>//isnum2larger?
18largest=num2;
19
20if<num3>largest>//isnum3larger?
21largest=num3;
22
23smallest=num1;//assumefirstnumberissmallest
24
25if<num2<smallest>
26smallest=num2;
27
28if<num3<smallest>
29smallest=num3;
30
31cout<<"Sumis"<<num1+num2+num3
32<<"\nAverageis"<<<num1+num2+num3>/3
33<<"\nProductis"<<num1*num2*num3
34<<"\nSmallestis"<<smallest
35<<"\nLargestis"<<largest<<endl;
36
37return0;
38}
Inputthreedifferentintegers:132714
Sumis54
Averageis18
Productis4914
Smallestis13
Largestis27
1.27Writeaprogramthatreadsintheradiusofacircleandprintsthecircle’sdiameter,circumferenceandarea.Usetheconstant
value3.14159forp.Dothesecalculationsinoutputstatements.<Note:Inthischapter,wehavediscussedonlyintegerconstants
andvariables.InChapter3wewilldiscussfloating-pointnumbers,i.e.,valuesthatcanhavedecimalpoints.>
1//Exercise1.27Solution
2#include<iostream>
3
4usingstd::cout;
5usingstd::endl;
6usingstd::cin;
7
8intmain<>
9{
10intradius;//declaration
11
12cout<<"Enterthecircleradius:";//prompt
13cin>>radius;//input
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
Chapter1IntroductiontoComputersandC++ProgrammingSolutions7
14
15cout<<"Diameteris"<<radius*2.0
16<<"\nCircumferenceis"<<2*3.14159*radius
17<<"\nAreais"<<3.14159*radius*radius<<endl;
18
19return0;
20}
Enterthecircleradius:8
Diameteris16
Circumferenceis50.2654
Areais201.062
1.28Writeaprogramthatprintsabox,anoval,anarrowandadiamondasfollows:
**************
*********
***********
*******
*******
*******
*******
*******
**************
1//Exercise1.28Solution
2#include<iostream>
3
4usingstd::cout;
5usingstd::endl;
6
7main<>
8{
9cout<<"**************\n"
10<<"*********\n"
11<<"***********\n"
12<<"*******\n"
13<<"*******\n"
14<<"*******\n"
15<<"*******\n"
16<<"*******\n"
17<<"**************"<<endl;
18
19return0;
20}
1.29Whatdoesthefollowingcodeprint?
cout<<"*\n**\n***\n****\n*****\n";
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
8IntroductiontoComputersandC++ProgrammingSolutionsChapter1
ANS:
*
**
***
****
*****
1.30Writeaprogramthatreadsinfiveintegersanddeterminesandprintsthelargestandthesmallestintegersinthegroup.Use
onlytheprogrammingtechniquesyoulearnedinthischapter.
1//Exercise1.30Solution
2#include<iostream>
3
4usingstd::cout;
5usingstd::endl;
6usingstd::cin;
7
8intmain<>
9{
10intnum1,num2,num3,num4,num5,largest,smallest;
11
12cout<<"Enterfiveintegers:";
13cin>>num1>>num2>>num3>>num4>>num5;
14
15largest=num1;
16smallest=num1;
17
18if<num1>largest>
19largest=num1;
20
21if<num2>largest>
22largest=num2;
23
24if<num3>largest>
25largest=num3;
26
27if<num4>largest>
28largest=num4;
29
30if<num5>largest>
31largest=num5;
32
33if<num1<smallest>
34smallest=num1;
35
36if<num2<smallest>
37smallest=num2;
38
39if<num3<smallest>
40smallest=num3;
41
42if<num4<smallest>
43smallest=num4;
44
45if<num5<smallest>
46smallest=num5;
47
48cout<<"Largestis"<<largest
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
Chapter1IntroductiontoComputersandC++ProgrammingSolutions9
49<<"\nSmallestis"<<smallest<<endl;
50
51return0;
52}
Enterfiveintegers:882287821
Largestis88
Smallestis8
1.31Writeaprogramthatreadsanintegeranddeterminesandprintswhetheritisoddoreven.<Hint:Usethemodulusoperator.
Anevennumberisamultipleoftwo.Anymultipleoftwoleavesaremainderofzerowhendividedby2.>
1//Exercise1.31Solution
2#include<iostream>
3
4usingstd::cout;
5usingstd::endl;
6usingstd::cin;
7
8intmain<>
9{
10intnum;
11
12cout<<"Enteranumber:";
13cin>>num;
14
15if<num%2==0>
16cout<<"Thenumber"<<num<<"iseven."<<endl;
17
18if<num%2!=0>
19cout<<"Thenumber"<<num<<"isodd."<<endl;
20
21return0;
22}
Enteranumber:73
Thenumber73isodd.
1.32Writeaprogramthatreadsintwointegersanddeterminesandprintsifthefirstisamultipleofthesecond.<Hint:Usethe
modulusoperator.>
1//Exercise1.32Solution
2#include<iostream>
3
4usingstd::cout;
5usingstd::endl;
6usingstd::cin;
7
8intmain<>
9{
10intnum1,num2;
11
12cout<<"Entertwointegers:";
13cin>>num1>>num2;
14
15if<num1%num2==0>
16cout<<num1<<"isamultipleof"<<num2<<endl;
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
10IntroductiontoComputersandC++ProgrammingSolutionsChapter1
17
18if<num1%num2!=0>
19cout<<num1<<"isnotamultipleof"<<num2<<endl;
20
21return0;
22}
Entertwointegers:228
22isnotamultipleof8
1.33Displayacheckerboardpatternwitheightoutputstatements,thendisplaythesamepatternwithasfewoutputstatements
aspossible.
********
********
********
********
********
********
********
********
1//Exercise1.33Solution
2#include<iostream>
3
4usingstd::cout;
5usingstd::endl;
6
7intmain<>
8{
9//Eightoutputstatements
10cout<<"********\n";
11cout<<"********\n";
12cout<<"********\n";
13cout<<"********\n";
14cout<<"********\n";
15cout<<"********\n";
16cout<<"********\n";
17cout<<"********\n\n";
18
19//Oneoutputstatement;3parts
20cout<<"********\n********\n********\n"
21<<"********\n********\n********\n"
22<<"********\n********\n";
23
24cout<<endl;//ensureeverythingisdisplayed
25
26return0;
27}
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
Chapter1IntroductiontoComputersandC++ProgrammingSolutions11
********
********
********
********
********
********
********
********
********
********
********
********
********
********
********
********
1.34Distinguishbetweenthetermsfatalerrorandnon–fatalerror.Whymightyouprefertoexperienceafatalerrorratherthan
anon–fatalerror?
ANS:Afatalerrorcausesaprogramtoterminateprematurely.Anonfatalerroroccurswhenthelogicoftheprogramis
incorrect,andtheprogramdoesnotworkproperly.Afatalerrorispreferredfordebuggingpurposes.Afatalerrorimmediately
letsyouknowthereisaproblemwiththeprogram,whereasanonfatalerrorcanbesubtleandpossiblygoundetected.
1.35Hereisapeekahead.Inthischapteryoulearnedaboutintegersandthetypeint.C++canalsorepresentuppercaseletters,
lowercaselettersandaconsiderablevarietyofspecialsymbols.C++usessmallintegersinternallytorepresenteachdifferentcharacter.
Thesetofcharactersacomputerusesandthecorrespondingintegerrepresentationsforthosecharactersiscalledthatcomputer’s
characterset.Youcanprintacharacterbysimplyenclosingthatcharacterinsinglequotesaswith
cout<<'A';
Youcanprinttheintegerequivalentofacharacterusingstatic_castasfollows:
cout<<static_cast<int><'A'>;
Thisiscalledacastoperation<weformallyintroducecastsinChapter2>.Whentheprecedingstatementexecutes,itprintsthe
value65<onsystemsthatusetheASCIIcharacterset>.Writeaprogramthatprintstheintegerequivalentsofsomeuppercaseletters,
lowercaseletters,digitsandspecialsymbols.Ataminimum,determinetheintegerequivalentsofthefollowing:ABCab
c012$*+/andtheblankcharacter.
1//Exercise1.35Solution
2#include<iostream>
3
4usingstd::cout;
5usingstd::endl;
6usingstd::cin;
7
8intmain<>
9{
10charsymbol;
11
12cout<<"Enteracharacter:";
13cin>>symbol;
14
15cout<<symbol<<"'sintegerequivalentis"
16<<static_cast<int><symbol><<endl;
17
18return0;
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
12IntroductiontoComputersandC++ProgrammingSolutionsChapter1
19}
Enteracharacter:A
A'sintegerequivalentis65
1.36Writeaprogramthatinputsafive-digitnumber,separatesthenumberintoitsindividualdigitsandprintsthedigitsseparated
fromoneanotherbythreespaceseach.<Hint:Usetheintegerdivisionandmodulusoperators.>Forexample,iftheusertypes
in42339theprogramshouldprint
42339
1//Exercise1.36Solution
2#include<iostream>
3
4usingstd::cout;
5usingstd::endl;
6usingstd::cin;
7
8intmain<>
9{
10intnum;
11
12cout<<"Enterafive-digitnumber:";
13cin>>num;
14
15cout<<num/10000<<"";
16num=num%10000;
17cout<<num/1000<<"";
18num=num%1000;
19cout<<num/100<<"";
20num=num%100;
21cout<<num/10<<"";
22num=num%10;
23cout<<num<<endl;
24
25return0;
26}
Enterafive-digitnumber:42339
42339
.2000.Deitel&Associates,Inc.andPrenticeHall.AllRightsReserved.
Chapter1IntroductiontoComputersandC++ProgrammingSolutions13
1.37Usingonlythetechniquesyoulearnedinthischapter,writeaprogramthatcalculatesthesquaresandcubesofthenumbers
from0to10andusestabstoprintthefollowingtableofvalues:
numbersquarecube
000
111
248
3927
41664
525125
636216
749
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025-2026学年外研版2024新教材七年级下册英语Unit 2 Understanding ideas 第一课时Reading教学设计
- 2026年贵州省遵义市高职单招职业技能考试题库含答案详细解析
- 2026年西安电力高等专科学校单招职业适应性测试题库带答案详细解析
- 2026年寿衣定制服务合同
- 2025年度体育场馆环境监测合同
- 2025-2026学年锻炼感官的教案
- 2026年轮机管理协议
- 2025-2026学年何的拼音教学设计
- 2025-2026学年高中英语教学设计素材网
- 2.3 生物群落(教学设计)九年级科学下册同步高效课堂(浙教版)
- 2026年江苏经贸职业技术学院单招综合素质考试题库附答案详解
- 2026河北衡水恒通热力有限责任公司公开招聘工作人员28名笔试备考试题及答案解析
- 2026春统编版(新教材)小学道德与法治一年级下册(全册)各单元知识点复习课件
- 吉水县2026年面向社会公开招聘农村(社区)“多员合一岗”工作人员【146人】笔试备考试题及答案解析
- 《工程勘察设计收费标准》(2002年修订本)-完整版-1
- 电子元器件选型规范
- 多彩贵州,魅力贵州
- 厦门医学院辅导员考试真题2022
- 有限公司450m3高炉项目初步设计安全专篇
- 热学李椿 电子
- 教学能力比赛决赛 《英语》教案
评论
0/150
提交评论