版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 阿尔茨海默病抗Aβ单抗治疗管理共识2026
- SL 618-2013 水利水电工程可行性研究报告编制规程
- 2025-2026学年人教版小学一年级下册数学口算专项练习(100以内加减法含答案)
- 器材借用免责协议书
- 2024年货物合同模板7篇
- 职中安全工作计划范文5篇
- CAPA 现场翻译器:纠正、纠正措施与预防措施到底差在哪
- 2025版三维设计 一轮 高中总复习物理第八章 机械振动与机械波
- 2024年全国助理医师之中医助理医师考试经典测试题详细参考解析
- 城市轨道交通应急处理教案4-项目二-客运组织突发事件应急处理-任务1突发大客流应急处理
- 2026贵州黔晟投资有限公司第一批社会招聘8人建设考试备考试题及答案解析
- 雅安市雨城区2026年公开考试选聘社区工作者(99人)建设考试参考试题及答案解析
- 2026年及未来5年市场数据中国聚酰亚胺行业市场调查研究及发展趋势预测报告
- 2026年北京市丰台区高三一模语文试题【含答案】
- (正式版)DB32∕T 2940-2016 《鲜食玉米品种 苏玉糯11》
- 河北建投校招笔试题库
- 销售成本管理培训课件
- ICU护士长2025年度述职报告
- 激光打标机安全培训课件
- 火车开啦音乐一年级教案
- 市政基础设施工程质量检验与验收统一标准(DBJ01-90-2004)
评论
0/150
提交评论