




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
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>
headerfileinaprogramthatinputsdatafromthekey-boardoroutputsdatatothescreencausesthecompilertoissueanerrormessage,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“l(fā)oaded”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等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 承包合同終止協(xié)議
- 木材公司銷售合同
- 平面模特拍攝合同
- 電力施工勞務(wù)合同
- 漫畫助理外包合同
- 油漆勞務(wù)分包合同協(xié)議書
- 無人機(jī)物流配送運(yùn)營(yíng)合作項(xiàng)目合同
- 商丘幼兒師范高等??茖W(xué)校《旅行社經(jīng)營(yíng)管理》2023-2024學(xué)年第二學(xué)期期末試卷
- 山東管理學(xué)院《高階地質(zhì)資源勘查與評(píng)價(jià)》2023-2024學(xué)年第二學(xué)期期末試卷
- 文華學(xué)院《地理科學(xué)類專業(yè)導(dǎo)論》2023-2024學(xué)年第二學(xué)期期末試卷
- 飛行器小學(xué)生課件
- 應(yīng)急突發(fā)處置
- 2024年定融認(rèn)購(gòu)協(xié)議合同范文
- 2024數(shù)據(jù)中心綜合布線工程產(chǎn)品選用指南
- 《檢驗(yàn)檢測(cè)機(jī)構(gòu)資質(zhì)認(rèn)定評(píng)審準(zhǔn)則》知識(shí)試題
- GCP培訓(xùn)課件教學(xué)課件
- 2023-2024學(xué)年廣東省廣州市天河區(qū)八年級(jí)(上)期末英語試卷
- 砸墻合同協(xié)議書(2篇)
- 2024加油站操作員安全培訓(xùn)考試題及答案
- GB/T 5267.5-2024緊固件表面處理第5部分:熱擴(kuò)散滲鋅層
- 全國(guó)醫(yī)療服務(wù)項(xiàng)目技術(shù)規(guī)范
評(píng)論
0/150
提交評(píng)論