C++程序设计英文课件:Ch2 Introduction to C++ Programming_第1页
C++程序设计英文课件:Ch2 Introduction to C++ Programming_第2页
C++程序设计英文课件:Ch2 Introduction to C++ Programming_第3页
C++程序设计英文课件:Ch2 Introduction to C++ Programming_第4页
C++程序设计英文课件:Ch2 Introduction to C++ Programming_第5页
已阅读5页,还剩74页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

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“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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论