




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
12Introductionto
C++Programming2OBJECTIVESInthischapteryou’lllearn:TowritesimplecomputerprogramsinC++.Towritesimpleinputandoutputstatements.Tousefundamentaltypes.Basiccomputermemoryconcepts.Tousearithmeticoperators.Theprecedenceofarithmeticoperators.Towritesimpledecision-makingstatements.32.1 Introduction2.2 FirstPrograminC++:PrintingaLineofText2.3 ModifyingOurFirstC++Program2.4 AnotherC++Program:AddingIntegers2.5 MemoryConcepts2.6 Arithmetic2.7 DecisionMaking:EqualityandRelationalOperators2.8 (Optional)SoftwareEngineeringCaseStudy:ExaminingtheATMRequirementsDocument2.9 Wrap-Up
42.1IntroductionC++programmingFacilitatesdisciplinedapproachtocomputerprogramdesignProgramsprocessinformationanddisplayresultsFiveexamplesdemonstrateHowtodisplaymessagesonthescreenHowtoobtaininformationfromtheuserHowtoperformarithmeticcalculationsHowtomakedecisionsbycomparingnumbers52.2FirstPrograminC++:PrintingaLineofTextSimpleprogramPrintsalineoftextIllustratesseveralimportantfeaturesofC++62.2FirstPrograminC++:PrintingaLineofText(Cont.)CommentsExplainprogramstoyouandotherprogrammersImproveprogramreadabilityIgnoredbycompilerSingle-linecommentBeginswith//Example//Thisisatext-printingprogram.Multi-linecommentStartswith
/*Endswith*/7Outlinefig02_01.cpp
(1of1)
fig02_01.cpp
output(1of1)
Single-linecommentsPreprocessordirectivetoincludeinput/outputstreamheaderfile<iostream>FunctionmainappearsexactlyonceineveryC++programFunctionmainreturnsanintegervalueLeftbrace{beginsfunctionbodyCorrespondingrightbrace}endsfunctionbodyStatementsendwithasemicolon;NamecoutbelongstonamespacestdStreaminsertionoperatorKeywordreturnisoneofseveralmeanstoexitafunction;value0indicatesthattheprogramterminatedsuccessfully8GoodProgrammingPractice2.1Everyprogramshouldbeginwithacommentthatdescribesthepurposeoftheprogram,author,dateandtime.(Wearenotshowingtheauthor,dateandtimeinthisbook’sprogramsbecausethisinformationwouldberedundant.)92.2FirstPrograminC++:PrintingaLineofText(Cont.)PreprocessordirectivesProcessedbypreprocessorbeforecompilingBeginwith#Example#include<iostream>Tellspreprocessortoincludetheinput/outputstreamheaderfile<iostream>WhitespaceBlanklines,spacecharactersandtabsUsedtomakeprogramseasiertoreadIgnoredbythecompiler10CommonProgrammingError2.1Forgettingtoincludethe<iostream>
headerfileinaprogramthatinputsdatafromthekeyboardoroutputsdatatothescreencausesthecompilertoissueanerrormessage,becausethecompilercannotrecognizereferencestothestreamcomponents(e.g.,cout).11GoodProgrammingPractice2.2Useblanklinesandspacecharacterstoenhanceprogramreadability.122.2FirstPrograminC++:PrintingaLineofText(Cont.)FunctionmainApartofeveryC++programExactlyonefunctioninaprogrammustbemainCanreturnavalueExampleintmain()Thismainfunctionreturnsaninteger(wholenumber)Bodyisdelimitedbybraces({})StatementsInstructtheprogramtoperformanactionAllstatementsendwithasemicolon(;)132.2FirstPrograminC++:PrintingaLineofText(Cont.)Namespacestd::Specifiesusinganamethatbelongsto“namespace”stdCanberemovedthroughtheuseofusingstatementsStandardoutputstreamobjectstd::cout“Connected”toscreenDefinedininput/outputstreamheaderfile<iostream>142.2FirstPrograminC++:PrintingaLineofText(Cont.)Streaminsertionoperator<<
Valuetoright(rightoperand)insertedintoleftoperandExamplestd::cout<<"Hello";Insertsthestring"Hello"intothestandardoutputDisplaystothescreenEscapecharactersAcharacterprecededby"\"Indicates“special”characteroutputExample"\n"Cursormovestobeginningofnextlineonthescreen15CommonProgrammingError2.2OmittingthesemicolonattheendofaC++statementisasyntaxerror.(Again,preprocessordirectivesdonotendinasemicolon.)Thesyntaxofaprogramminglanguagespecifiestherulesforcreatingaproperprograminthatlanguage.AsyntaxerroroccurswhenthecompilerencounterscodethatviolatesC++’slanguagerules(i.e.,itssyntax).Thecompilernormallyissuesanerrormessagetohelptheprogrammerlocateandfixtheincorrectcode.(cont…)16CommonProgrammingError2.2Syntaxerrorsarealsocalledcompilererrors,compile-timeerrorsorcompilationerrors,becausethecompilerdetectsthemduringthecompilationphase.Youwillbeunabletoexecuteyourprogramuntilyoucorrectallthesyntaxerrorsinit.Asyou’llsee,somecompilationerrorsarenotsyntaxerrors.172.2FirstPrograminC++:PrintingaLineofText(Cont.)returnstatementOneofseveralmeanstoexitafunctionWhenusedattheendofmainThevalue0indicatestheprogramterminatedsuccessfullyExamplereturn0;18GoodProgrammingPractice2.3Manyprogrammersmakethelastcharacterprintedbyafunctionanewline(\n).Thisensuresthatthefunctionwillleavethescreencursorpositionedatthebeginningofanewline.Conventionsofthisnatureencouragesoftwarereusability—akeygoalinsoftwaredevelopment.19Fig.2.2
|Escapesequences.20GoodProgrammingPractice2.4Indenttheentirebodyofeachfunctiononelevelwithinthebracesthatdelimitthebodyofthefunction.Thismakesaprogram’sfunctionalstructurestandoutandhelpsmaketheprogrameasiertoread.21GoodProgrammingPractice2.5Setaconventionforthesizeofindentyouprefer,thenapplyituniformly.Thetabkeymaybeusedtocreateindents,buttabstopsmayvary.Werecommendusingeither1/4-inchtabstopsor(preferably)threespacestoformalevelofindent.222.3ModifyingOurFirstC++ProgramTwoexamplesPrinttextononelineusingmultiplestatements(Fig.2.3)EachstreaminsertionresumesprintingwherethepreviousonestoppedPrinttextonseverallinesusingasinglestatement(Fig.2.4)EachnewlineescapesequencepositionsthecursortothebeginningofthenextlineTwonewlinecharactersback-to-backoutputsablankline23Outlinefig02_03.cpp
(1of1)fig02_03.cppoutput(1of1)Multiplestreaminsertionstatementsproduceonelineofoutputbecauseline8endswithoutanewline24Outlinefig02_04.cpp
(1of1)fig02_04.cppoutput
(1of1)Usenewlinecharacterstoprintonmultiplelines252.4AnotherC++Program:AddingIntegersVariableIsalocationinmemorywhereavaluecanbestoredCommondatatypes(fundamental,primitiveorbuilt-in)int–forintegernumberschar–forcharactersdouble–forfloatingpointnumbersDeclarevariableswithdatatypeandnamebeforeuseintinteger1;intinteger2;intsum;26Outlinefig02_05.cpp
(1of1)fig02_05.cppoutput(1of1)DeclareintegervariablesUsestreamextractionoperatorwithstandardinputstreamtoobtainuserinputStreammanipulatorstd::endloutputsanewline,then“flushes”outputbufferConcatenating,chainingorcascadingstreaminsertionoperations272.4AnotherC++Program:AddingIntegers(Cont.)Variables(Cont.)YoucandeclareseveralvariablesofsametypeinonedeclarationComma-separatedlistintinteger1,integer2,sum;VariablenameMustbeavalididentifierSeriesofcharacters(letters,digits,underscores)CannotbeginwithdigitCasesensitive(uppercaselettersaredifferentfromlowercaseletters)28GoodProgrammingPractice2.6Placeaspaceaftereachcomma(,)
tomakeprogramsmorereadable.29GoodProgrammingPractice2.7Someprogrammersprefertodeclareeachvariableonaseparateline.Thisformatallowsyoutoplaceadescriptivecommentnexttoeachdeclaration.30PortabilityTip2.1C++allowsidentifiersofanylength,butyourC++implementationmayimposesomerestrictionsonthelengthofidentifiers.Useidentifiersof31charactersorfewertoensureportability.31GoodProgrammingPractice2.8Choosingmeaningfulidentifiershelpsmakeaprogramself-documenting—apersoncanunderstandtheprogramsimplybyreadingitratherthanhavingtorefertomanualsorcomments.32GoodProgrammingPractice2.9Avoidusingabbreviationsinidentifiers.Thispromotesprogramreadability.33GoodProgrammingPractice2.10Avoididentifiersthatbeginwithunderscoresanddoubleunderscores,becauseC++compilersmayusenameslikethatfortheirownpurposesinternally.Thiswillpreventnamesyouchoosefrombeingconfusedwithnamesthecompilerschoose.34Error-PreventionTip2.1LanguageslikeC++are“movingtargets.”Astheyevolve,morekeywordscouldbeaddedtothelanguage.Avoidusing“loaded”wordslike“object”asidentifiers.Eventhough“object”isnotcurrentlyakeywordinC++,itcouldbecomeone;therefore,futurecompilingwithnewcompilerscouldbreakexistingcode.35GoodProgrammingPractice2.11Alwaysplaceablanklinebetweenadeclarationandadjacentexecutablestatements.Thismakesthedeclarationsstandoutintheprogramandcontributestoprogramclarity.36GoodProgrammingPractice2.12Ifyouprefertoplacedeclarationsatthebeginningofafunction,separatethemfromtheexecutablestatementsinthatfunctionwithoneblanklinetohighlightwherethedeclarationsendandtheexecutablestatementsbegin.372.4AnotherC++Program:AddingIntegers(Cont.)Inputstreamobjectstd::cinfrom<iostream>UsuallyconnectedtokeyboardStreamextractionoperator>>Waitsforusertoinputvalue,pressEnter(Return)keyStoresavalueinthevariabletotherightoftheoperatorConvertsthevaluetothevariable’sdatatypeExamplestd::cin>>number1;ReadsanintegertypedatthekeyboardStorestheintegerinvariablenumber1382.4AnotherC++Program:AddingIntegers(Cont.)Assignmentoperator=AssignsthevalueontherighttothevariableontheleftBinaryoperator(twooperands)Example:sum=variable1+variable2;Addsthevaluesofvariable1andvariable2StorestheresultinthevariablesumStreammanipulatorstd::endlOutputsanewlineFlushestheoutputbuffer39GoodProgrammingPractice2.13Placespacesoneithersideofabinaryoperator.Thismakestheoperatorstandoutandmakestheprogrammorereadable.402.4AnotherC++Program:AddingIntegers(Cont.)ConcatenatingstreaminsertionoperationsUsemultiplestreaminsertionoperatorsinasinglestatementStreaminsertionoperationknowshowtooutputeachtypeofdataAlsocalledchainingorcascadingExamplestd::cout<<"Sumis"<<number1+number2
<<std::endl;Outputs"Sumis“Thenoutputsthesumofvariablesnumber1andnumber2Thenoutputsanewlineandflushestheoutputbuffer412.5MemoryConceptsVariablenamesCorrespondtoactuallocationsinthecomputer'smemoryEveryvariablehasaname,atype,asizeandavalueWhenanewvalueplacedintoavariable,thenewvalueoverwritestheoldvalueWritingtomemoryis“destructive”ReadingvariablesfrommemoryisnondestructiveExamplesum=number1+number2;Althoughthevalueofsum
is
overwrittenThevaluesofnumber1andnumber2
remainintact42Fig.2.6
|Memorylocationshowingthenameandvalueofvariablenumber1.43Fig.2.7
|Memorylocationsafterstoringvaluesfornumber1andnumber2.44Fig.2.8
|Memorylocationsaftercalculatingandstoringthesumofnumber1andnumber2.452.6ArithmeticArithmeticoperators*
Multiplication/
DivisionIntegerdivisiontruncates(discards)theremainder7/5evaluatesto1%Themodulusoperatorreturnstheremainder7%5evaluatesto246CommonProgrammingError2.3Attemptingtousethemodulusoperator(%)withnonintegeroperandsisacompilationerror.472.6Arithmetic(Cont.)Straight-lineformRequiredforarithmeticexpressionsinC++Allconstants,variablesandoperatorsappearinastraightlineGroupingsubexpressionsParenthesesareusedinC++expressionstogroupsubexpressionsInthesamemannerasinalgebraicexpressionsExamplea*(b+c)Multipleatimesthequantityb+c48Fig.2.9
|Arithmeticoperators.492.6Arithmetic(Cont.)RulesofoperatorprecedenceOperatorsinparenthesesareevaluatedfirstFornested(embedded)parenthesesOperatorsininnermostpairareevaluatedfirstMultiplication,divisionandmodulusareappliednextOperatorsareappliedfromlefttorightAdditionandsubtractionareappliedlastOperatorsareappliedfromlefttoright50Fig.2.10
|Precedenceofarithmeticoperators.51CommonProgrammingError2.4Someprogramminglanguagesuseoperators**or^
torepresentexponentiation.C++doesnotsupporttheseexponentiationoperators;usingthemforexponentiationresultsinerrors.52GoodProgrammingPractice2.14Usingredundantparenthesesincomplexarithmeticexpressionscanmaketheexpressionsclearer.53Fig.2.11
|Orderinwhichasecond-degreepolynomialisevaluated.542.7DecisionMaking:EqualityandRelationalOperatorsConditionExpressioncanbeeithertrueorfalseCanbeformedusingequalityorrelationaloperatorsifstatementIftheconditionistrue,thebodyoftheifstatementexecutesIftheconditionisfalse,thebodyoftheifstatementdoesnotexecute55Fig.2.12
|Equalityandrelationaloperators.56CommonProgrammingError2.5Asyntaxerrorwilloccurifanyoftheoperators==,!=,>=and<=
appearswithspacesbetweenitspairofsymbols.57CommonProgrammingError2.6Reversingtheorderofthepairofsymbolsinanyoftheoperators!=,>=and<=(bywritingthemas=!,=>
and=<,respectively)isnormallyasyntaxerror.Insomecases,writing!=
as=!
willnotbeasyntaxerror,butalmostcertainlywillbealogicerrorthathasaneffectatexecutiontime.(cont…)58CommonProgrammingError2.6YouwillunderstandwhywhenyoulearnaboutlogicaloperatorsinChapter
5.Afatallogicerrorcausesaprogramtofailandterminateprematurely.Anonfatallogicerrorallowsaprogramtocontinueexecuting,butusuallyproducesincorrectresults.
59CommonProgrammingError2.7Confusingtheequalityoperator==
withtheassignmentoperator=
resultsinlogicerrors.Theequalityoperatorshouldberead“isequalto,”andtheassignmentoperatorshouldberead“gets”or“getsthevalueof”or“isassignedthevalueof.”Somepeopleprefertoreadtheequalityoperatoras“doubleequals.”AswediscussinSection
5.9,confusingtheseoperatorsmaynotnecessarilycauseaneasy-to-recognizesyntaxerror,butmaycauseextremelysubtlelogicerrors.
60Outlinefig02_13.cpp
(1of2)usingdeclarationseliminatetheneedforstd::prefixYoucanwritecoutandcinwithoutstd::prefixDeclaringvariablesifstatementcomparesthevaluesofnumber1andnumber2totestforequalityIftheconditionistrue(i.e.,thevaluesareequal),executethisstatementifstatementcomparesvaluesofnumber1andnumber2totestforinequalityIftheconditionistrue(i.e.,thevaluesarenotequal),executethisstatementComparestwonumbersusingrelationaloperators<and>61Outlinefig02_13.cpp
(2of2)fig02_13.cppoutput(1of3)(2of3)(3of3)Comparestwonumbersusingtherelationaloperators<=and>=62GoodProgrammingPractice2.15Placeusingdeclarationsimmediatelyafterthe#includetowhichtheyrefer.63GoodProgrammingPractice2.16Indentthestatement(s)inthebodyofanifstatementtoenhancereadability.64GoodProgrammingPractice2.17Forreadability,thereshouldbenomorethanonestatementperlineinaprogram.65CommonProgrammingError2.8Placingasemicolonimmediatelyaftertherightparenthesisaftertheconditioninanifstatementisoftenalogicerror(althoughnotasyntaxerror).Thesemicoloncausesthebodyoftheifstatementtobeempty,sotheifstatementperformsnoaction,regardlessofwhetherornotitsconditionistrue.Worseyet,theoriginalbodystatementoftheifstatementnowwouldbecomeastatementinsequencewiththeifstatementandwouldalwaysexecute,oftencausingtheprogramtoproduceincorrectresults.66CommonProgrammingError2.9Itisasyntaxerrortosplitanidentifierbyinsertingwhite-spacecharacters(e.g.,writingmainasmain).67GoodProgrammingPractice2.18Alengthystatementmaybespreadoverseverallines.Ifasinglestatementmustbesplitacrosslines,choosemeaningfulbreakingpoints,suchasafteracommainacomma-separatedlist,orafteranoperatorinalengthyexpression.Ifastatementissplitacrosstwoormorelines,indentallsubsequentlinesandleft-alignthegroupofindented.68Fig.2.14
|Precedenceandassociativityoftheoperatorsdiscussedsofar.69GoodProgrammingPractice2.19Refertotheoperatorprecedenceandassociativitychartwhenwritingexpressionscontainingmanyoperators.Confirmthattheoperatorsintheexpressionareperformedintheorderyouexpect.Ifyouareuncertainabouttheorderofevaluationinacomplexexpression,breaktheexpressionintosmallerstatementsoruseparenthesestoforcetheorderofevaluation,exactlyasyouwoulddoinanalgebraicexpression.Besuretoobservethatsomeoperatorssuchasassignment(=)associaterighttoleftratherthanlefttoright.702.8
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2024-2025学年高中历史 第三单元 欧美资产阶级革命时代的杰出人物 第1课 英国革命的领导者克伦威尔(2)教学教学实录 新人教版选修4
- 2 丁香结 第二课时 教学设计-2024-2025学年语文六年级上册统编版
- 电影娱乐产业在线票务系统开发
- 电子元器件基础知识与选购操作手册(含图解)
- 区块链技术在环保领域的应用预案
- 2023一年级数学上册 八 认识钟表(小明的一天)配套教学实录 北师大版
- 6景阳冈教学设计-2023-2024学年五年级下册语文统编版
- 3不懂就要问教学设计-2024-2025学年三年级上册语文统编版
- 2023一年级数学上册 5 6~10的认识和加减法练习课(6-8)教学实录 新人教版
- 2024年五年级品社下册《多彩的世界民俗》教学实录 沪教版
- 2025年中考道德与法治时政热点专题复习:凝聚榜样力量 坚定文化自信(含练习题及答案)
- 租赁单位消防安全管理协议书
- 护理条码贴错品管圈
- 水利工程旋挖桩施工方案
- 污水一体化项目施工方案与技术措施
- 组织行为学测试试题库与答案
- 2024年河南省公务员录用考试《行测》试题及答案解析
- 2024年北京海淀区初一(上)期中语文试题(含答案)
- 初二美术教学课件模板
- 装配式叠合板安装施工方案
- 2024年江苏常州机电职业技术学院招聘44人历年高频难、易错点500题模拟试题附带答案详解
评论
0/150
提交评论