C++面向对象程序设计第六版第一章编程题答案.docx
《C++面向对象程序设计第六版第一章编程题答案.docx》由会员分享,可在线阅读,更多相关《C++面向对象程序设计第六版第一章编程题答案.docx(9页珍藏版)》请在冰豆网上搜索。
C++面向对象程序设计第六版第一章编程题答案
INSTRUCTOR’SRESOURCEGUIDE
SOLUTIONSTOPROGRAMMINGPROJECTS
TOACCOMPANY
PROBLEM
SOLVING
WITH
C++
THEOBJECT
OFPROGRAMMING
SixthEdition
WalterSavitch
UNIVERSITYOFCALIFORNIA,SANDIEGO
Thisinstructor’smanualisbasedonthefourthedition.
http:
//www.aw-
andpleasevisitourgeneralcomputerscienceandengineeringwebsiteat:
http:
//www.aw-
Copyright©2007byAddison-WesleyPublishingCompany
Allrightreserved.Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,ortransmitted,inanyformorbyanymeans,electronic,mechanical,photo-copying,recording,oranyothermediaembodimentsnowknownorhereaftertobecomeknown,withoutthepriorwrittenpermissionofthepublisher.ManufacturedintheUnitedStatesofAmerica.
Manyofthedesignationsusedbymanufacturersandsellerstodistinguishtheirproductsareclaimedastrademarks.Wherethesedesignationsappearinthisbook,andthepublisherwasawareofatrademarkclaim,thedesignationshavebeenprintedininitialcapsorallcaps.
Theprogramsandtheapplicationspresentedinthisbookhavebeenincludedfortheirinstructionalvalue.Theyhavebeentestedwithcarebutarenotguaranteedforanyparticularpurpose.Thepublisherdoesnotofferanywarrantiesorrepresentations,nordoesitacceptanyliabilitieswithrespecttotheprogramsorapplications.
Addison-WesleyPublishingCompany
2725SandHillRoad
MenloPark,CA94025
Contents
Preface
Chapter1IntroductiontoComputersandC++Programming
Chapter2C++Basics
Chapter3MoreFlowofControl
Chapter4ProceduralAbstractionandFunctionsthatReturnaValue
Chapter5FunctionsforallSubtasks
Chapter6I/OStreamsasanIntroductiontoObjectsandClasses
Chapter7Arrays
Chapter8StringsandVectors
Chapter9PointersandDynamicArrays
Chapter10DefiningClasses
Chapter11FriendsandOverloadedOperators
Chapter12SeparateCompilationandNamespaces
Chapter13PointersandLinkedLists
Chapter14Recursion
Chapter15Inheritance
Chapter16ExceptionHandling
Chapter17Templates
Chapter18StandardTemplateLibrary
Preface
Thisisadocumentthatismeanttobeasupplementthetextfortheinstructor.Thereisadiscussionoftheideasineachchapter,teachingsuggestions,andsomesupplementaryideas.Therearesolutionstomanyoftheprogrammingproblems.Someproblemshaveseveraldifferentsolutionsthatcorrespondtodifferentpathsthroughthebook.Thereare25to50testquestionswithanswersanddiscussionforeachchapter.Thequestionsareofbothshortanswer(multiplechoice,truefalse,fillintheblank)typeaswellasread-the-codequestionsandshortprogrammingproblems.Iurgethatexplanationstotheshortanswerquestionsberequiredofthestudent.
Withregardtothecontentofthismanual,itshouldbenotedthatC++leavesmanyoptionsonhowtodoanyproblem,andanybookwillnecessarilychooseasubsettopresent.Ourauthorhasmadesuchasetofchoices.IhavealsomadewhatIhopeisacomplementarysetofchoicesforthisInstructor'sresourceManual.Iamstrivingtoproduceacomplementarydocumenttothetext,adocumentfortheinstructor,butInecessarilywilldosomethingsdifferently.PleasedonotholdthestudentresponsibleforwhatIhaveputhere.Thereaderofthisdocumentmustnotethatitisnecessarytoreadthetext,asthatiswhatthestudenthastoworkwith.Inspiteofoureffortsatconsistencyofcontentandstyle,therewillbesomevariancebetweensomeofthepresentationhereandthepresentationinthetext.
Thecodehasbeencompiledandtestedwithg++(gcc3.4.4),VisualStudioC++.NET2003,VisualStudioC++.NET2005,VisualStudioC++Express.NET,andVisualStudioC++6.0updatedtoservicepack6.UsersofMicrosoftVisualStudioC++6.0mayexperiencethemostincompatibilitiesandshouldensurethatservicepack6isdownloadedandinstalledfromtheMicrosoftwebsite.ThetextusesonlymainstreamfeaturesofC++,consequently,mostcompilerswillcompilethecodeandproduceoutputthatdoesnotdiffersignificantlyfromtheresultspresentedhere.Wehaveattemptedtosupplywarningswhereanyofthesecompilersgivestrouble.
Instructor'sResourceManual
for
Savitch,ProblemSolvingwithC++:
TheObjectofProgramming.
Chapter1
IntroductiontoComputersandC++Programming
ThisdocumentisintendedtobearesourceguideforinstructorsusingSavitch,ProblemSolvingwithC++:
TheObjectofProgramming.Thisguidefollowsthetextchapterbychapter.Eachchapterofthisguidecontainsthefollowingsections:
1.Outlineoftopicsinthechapter
2.Generalremarksonthechapter
3.Solutionsto,andremarkson,selectedProgrammingProjects
4.TestQuestions
5.AnswerstothetestQuestion
SolutionsandremarksonselectedProgrammingProjects
Theseprogrammingexercisesareintendedtohelpfamiliarizethestudentwiththeprogrammingenvironment.Solutionsareverysystemdependent.Consequently,onlyonesolutionisprovidedfortheprogrammingprojectsinthischapter.
//Ch1Proj8.cpp
//
//Thisprogramcalculatesthemonetaryvalueofanumberof
//quarters,dimes,andnickels.
//***********************************************************************
#include
usingnamespacestd;
//====================
//mainfunction
//====================
intmain()
{
intquarters,dimes,nickels,total;
//Inputcoins
cout<<"Enternumberofquarters."<cin>>quarters;
cout<<"Enternumberofdimes."<cin>>dimes;
cout<<"Enternumberofnickels."<cin>>nickels;
//Calculateandoutputtotal
total=(quarters*25)+(dimes*10)+(nickels*5);
cout<<"Themonetaryvalueofyourcoinsis"<return0;
}
OutlineofTopicsintheChapter1
1.1ComputerSystems
1.2ProgrammingandProblem-Solving
1.3IntroductiontoC++
1.4TestingandDebugging
Suggestedcourseoutlines:
ThereseemtobethreemajorapproachestoteachingC++asthefirstcourseinprogramming.Intheoneapproach,classesandobjectsaredoneveryearly,frequentlywithalibraryofsomesortthatmustbeusedwiththetext.Inanother,alloftheANSICsubsetofC++iscoveredpriortoevenmentioningclassesorobjects.Thistexttakesathirdroadthatismoremiddleoftheroad.Here,enoughofthecontrolconstructsandfunctionsarecoveredpriortodoingclassesandobjects.However,reorderingsofthechaptersarepossiblethatallowanyoftheseapproaches.
Hereisa"classesearly"coursethatfollowsthetextclosely.Thisoutlineassumesnobackgroundincomputing.TopicsbeyondChapter11maybestudiedastimepermits.
Daydaysallotted
11Startupbusiness
2-32Chapter1:
IntroductiontoComputers
4-85Chapter2:
C++Basics.Ifthestudentshaveprogrammingexperience,thetimespentcanbesignificantlyreduced.
9-113Chapter3:
ProceduralAbstractionandfunctionsthatreturnavalue
12-143Chapter4:
Functionsforallsubtasks
Test1
16-183Chapter5:
I/OStreamsasintroductiontoObjectsandClasses
19-224Chapter6:
DefiningClasses
23-275Chapter7:
MoreFlowofControl
Test2
29-324Chapter8:
FriendsandOverloadedOperators
Chapter9SeparateCompilationandNamespaces
33-375Chapter10:
Arrays
38-413Chapter11:
StringsandVectors
Test3
5Chapter12Pointers,DynamicArrays
3Chapter13Recursion
3Chapter14:
Templates
3Chapter15:
PointersandLinkedLists
3Chapter16:
Inheritance
3Chapter17:
ExceptionHandling
Reorderings:
TheauthorsuggestsareorderingintheprefacethatallowalmostallofANSIC(withthetighterC++type-checking)tobecoveredbeforeclasses.Severalvariantsonthisreorderingthatallowclassesabitearlierarepresentedinthetext.Theauthordescribesinterdependencyofthechaptersintheprefaceofthetext.Otherreorderingsarecertainlypossible.
Chapter1:
Thestudentshoulddoalltheprogrammingassignmentsinthischapter.Theseteachthelocallyavailableprogramdevelopmentsystemandfamiliarizethestudentwithsomeofthemorecommoncompilererrors.Errormessagesarequitespecifictothecompilerbeingused.Itisveryimportantthatthestudentlearntheseideasasearlyaspossible.
Outlineoftopicsinthechapter:
1.1ComputerSystems
1.2ProgrammingandProblem-Solving
1.3IntroductiontoC++
1.4TestingandDebugging
Generalremarksonthechapter
Thischapterservesasanintroductiontocomputersandthelanguageofcomputersforthosestudentswhohavenocomputerexperience.Theterminologyisveryimportant.Manystudentsonlywanttolearnhowtheprogramminglanguageworks,andseemtobeunhappywhentheyfindthattheyarerequiredtolearntheterminologyassociatedwiththelanguage.Thestudentswholearntheterminologyhavelesstroublebyfarwiththiscourse.
Studentsshouldbegivenanindicationoftheamountofworkthatmustbedonebeforecodingbegins.Thereareinstanceswhereseveralman-yearsofworkhavegoneintosoftwarebeforeasinglelineofcodewaswritten.
Emphasizetheimportanceoftheproblem-solvingphaseofprogramdesign.Thiswillsavethestudentworkinthelongrun.Itisfurtherimportanttoemphasizethattheproblemdefinitionandalgorithmdesignphasesmayneedcorrectingoncetheactualcodingandtestingisinprocess.Thisistrueevenifthealgorithmwascarefullydesktoptested.Emphasizethattheprogramdesignprocessisan'iterative'process.Youmakeastart,test,correctandrepeatuntilyouhaveasolution.
Itisafactthatthesoonerthecodingisstarted(onmostproblems),thelongertheproblemwilltaketofinish.Mystudentsinsi