SavitchSavitch_ch_02_第1页
SavitchSavitch_ch_02_第2页
SavitchSavitch_ch_02_第3页
SavitchSavitch_ch_02_第4页
SavitchSavitch_ch_02_第5页
已阅读5页,还剩92页未读 继续免费阅读

下载本文档

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

文档简介

Chapter2,C+Basics,Overview,2.1VariablesandAssignments2.2InputandOutput2.3DataTypesandExpressions2.4SimpleFlowofControl2.5ProgramStyle,Slide2-3,2.1,VariablesandAssignments,VariablesandAssignments,VariablesarelikesmallblackboardsWecanwriteanumberonthemWecanchangethenumberWecanerasethenumberC+variablesarenamesformemorylocationsWecanwriteavalueinthemWecanchangethevaluestoredthereWecannoterasethememorylocationSomevalueisalwaysthere,Slide2-5,Display2.1,Identifiers,VariablesnamesarecalledidentifiersChoosingvariablenamesUsemeaningfulnamesthatrepresentdatatobestoredFirstcharactermustbealettertheunderscorecharacterRemainingcharactersmustbelettersnumbersunderscorecharacter,Slide2-6,Keywords,Keywords(alsocalledreservedwords)AreusedbytheC+languageMustbeusedastheyaredefinedintheprogramminglanguageCannotbeusedasidentifiers,Slide2-7,DeclaringVariables(Part1),Beforeuse,variablesmustbedeclaredTellsthecompilerthetypeofdatatostoreExamples:intnumber_of_bars;doubleone_weight,total_weight;intisanabbreviationforinteger.couldstore3,102,3211,-456,etc.number_of_barsisoftypeintegerdoublerepresentsnumberswithafractionalcomponentcouldstore1.34,4.0,-345.6,etc.one_weightandtotal_weightarebothoftypedouble,DeclaringVariables(Part2),Immediatelypriortouseintmain()intsum;sum=score1+score2;return0;,Slide2-9,Atthebeginningintmain()intsum;sum=score1+score2;return0;,Twolocationsforvariabledeclarations,DeclaringVariables(Part3),Declarationsyntax:Type_nameVariable_1,Variable_2,.;DeclarationExamples:doubleaverage,m_score,total_score;doublemoon_distance;intage,num_students;intcars_waiting;,Slide2-10,AssignmentStatements,Anassignmentstatementchangesthevalueofavariabletotal_weight=one_weight+number_of_bars;total_weightissettothesumone_weight+number_of_barsAssignmentstatementsendwithasemi-colonThesinglevariabletobechangedisalwaysontheleftoftheassignmentoperator=OntherightoftheassignmentoperatorcanbeConstants-age=21;Variables-my_cost=your_cost;Expressions-circumference=diameter*3.14159;,Slide2-11,AssignmentStatementsandAlgebra,The=operatorinC+isnotanequalsignThefollowingstatementcannotbetrueinalgebranumber_of_bars=number_of_bars+3;InC+itmeansthenewvalueofnumber_of_barsisthepreviousvalueofnumber_of_barsplus3,Slide2-12,InitializingVariables,DeclaringavariabledoesnotgiveitavalueGivingavariableitsfirstvalueisinitializingthevariableVariablesareinitializedinassignmentstatementsdoublempg;/declarethevariablempg=26.3;/initializethevariableDeclarationandinitializationcanbecombinedusingtwomethodsMethod1doublempg=26.3,area=0.0,volume;Method2doublempg(26.3),area(0.0),volume;,Slide2-13,Section2.1Conclusion,CanyouDeclareandinitializetwointegersvariablestozero?Thevariablesarenamedfeetandinches.Declareandinitializetwovariables,oneintandonedouble?Bothshouldbeinitializedtotheappropriateformof5.Givegoodvariablenamesforidentifierstostorethespeedofanautomobile?anhourlypayrate?thehighestscoreonanexam?,Slide2-14,2.2,InputandOutput,InputandOutput,AdatastreamisasequenceofdataTypicallyintheformofcharactersornumbersAninputstreamisdatafortheprogramtouseTypicallyoriginatesatthekeyboardatafileAnoutputstreamistheprogramsoutputDestinationistypicallythemonitorafile,Slide2-16,Outputusingcout,coutisanoutputstreamsendingdatatothemonitorTheinsertionoperatorinsertsdataintocoutExample:coutnumber_of_barscandybarsn;ThislinesendstwoitemstothemonitorThevalueofnumber_of_barsThequotedstringofcharacterscandybarsnNoticethespacebeforethecincandyThencausesanewlinetobestartedfollowingthesinbarsAnewinsertionoperatorisusedforeachitemofoutput,Slide2-17,ExamplesUsingcout,Thisproducesthesameresultastheprevioussamplecoutnumber_of_bars;coutcandybarsn;HerearithmeticisperformedinthecoutstatementcoutTotalcostis$(price+tax);Quotedstringsareenclosedindoublequotes(Walter)Dontusetwosinglequotes()Ablankspacecanalsobeinsertedwithcout;iftherearenostringsinwhichaspaceisdesiredasincandybarsn,Slide2-18,IncludeDirectives,IncludeDirectivesaddlibraryfilestoourprogramsTomakethedefinitionsofthecinandcoutavailabletotheprogram:#includeUsingDirectivesincludeacollectionofdefinednamesTomakethenamescinandcoutavailabletoourprogram:usingnamespacestd;,Slide2-19,EscapeSequences,EscapesequencestellthecompilertotreatcharactersinaspecialwayistheescapecharacterTocreateanewlineinoutputusencoutn;ortheneweralternativecoutendl;Otherescapesequences:t-atab-abackslashcharacter-aquotecharacter,Slide2-20,FormattingRealNumbers,Realnumbers(typedouble)produceavarietyofoutputsdoubleprice=78.5;coutThepriceis$priceendl;Theoutputcouldbeanyofthese:Thepriceis$78.5Thepriceis$78.500000Thepriceis$7.850000e01Themostunlikelyoutputis:Thepriceis$78.50,Slide2-21,ShowingDecimalPlaces,coutincludestoolstospecifytheoutputoftypedoubleTospecifyfixedpointnotationsetf(ios:fixed)Tospecifythatthedecimalpointwillalwaysbeshownsetf(ios:showpoint)Tospecifythattwodecimalplaceswillalwaysbeshownprecision(2)Example:cout.setf(ios:fixed);cout.setf(ios:showpoint);cout.precision(2);coutThepriceisprice)removesdatatobeusedExample:coutnumber_of_bars;cinone_weight;ThiscodepromptstheusertoenterdatathenreadstwodataitemsfromcinThefirstvaluereadisstoredinnumber_of_barsThesecondvaluereadisstoredinone_weightDataisseparatedbyspaceswhenentered,Slide2-23,ReadingDataFromcin,MultipledataitemsareseparatedbyspacesDataisnotreaduntiltheenterkeyispressedAllowsusertomakecorrectionsExample:cinv1v2v3;RequiresthreespaceseparatedvaluesUsermighttype344512,Slide2-24,DesigningInputandOutput,Prompttheuserforinputthatisdesiredcoutstatementsprovideinstructionscoutage;NoticetheabsenceofanewlinebeforeusingcinEchotheinputbydisplayingwhatwasreadGivestheuserachancetoverifydatacoutagewasentered.symbol1symbol2;UsernormallyseparatedataitemsbyspacesJDResultsarethesameifthedataisnotseparatedbyspacesJD,Slide2-36,Display2.3,Typestring,stringisaclass,differentfromtheprimitivedatatypesdiscussedsofarDifferenceisdiscussedinChapter8UsedoublequotesaroundthetexttostoreintothestringvariableRequiresthefollowingbeaddedtothetopofyourprogram:#includeTodeclareavariableoftypestring:stringname=ApuNahasapeemapetilon;,Slide2-37,Display2.4,TypeCompatibilities,IngeneralstorevaluesinvariablesofthesametypeThisisatypemismatch:intint_variable;int_variable=2.99;Ifyourcompilerallowsthis,int_variablewillmostlikelycontainthevalue2,not2.99,Slide2-38,intdouble(part1),Variablesoftypedoubleshouldnotbeassignedtovariablesoftypeintintint_variable;doubledouble_variable;double_variable=2.00;int_variable=double_variable;Ifallowed,int_variablecontains2,not2.00,Slide2-39,intdouble(part2),Integervaluescannormallybestoredinvariablesoftypedoubledoubledouble_variable;double_variable=2;double_variablewillcontain2.0,Slide2-40,charint,Thefollowingactionsarepossiblebutgenerallynotrecommended!Itispossibletostorecharvaluesinintegervariablesintvalue=A;valuewillcontainanintegerrepresentingAItispossibletostoreintvaluesincharvariablescharletter=65;,Slide2-41,boolint,Thefollowingactionsarepossiblebutgenerallynotrecommended!ValuesoftypeboolcanbeassignedtointvariablesTrueisstoredas1Falseisstoredas0ValuesoftypeintcanbeassignedtoboolvariablesAnynon-zerointegerisstoredastrueZeroisstoredasfalse,Slide2-42,Arithmetic,Arithmeticisperformedwithoperators+foraddition-forsubtraction*formultiplication/fordivisionExample:storingaproductinthevariabletotal_weighttotal_weight=one_weight*number_of_bars;,Slide2-43,ResultsofOperators,ArithmeticoperatorscanbeusedwithanynumerictypeAnoperandisanumberorvariableusedbytheoperatorResultofanoperatordependsonthetypesofoperandsIfbothoperandsareint,theresultisintIfoneorbothoperandsaredouble,theresultisdouble,Slide2-44,DivisionofDoubles,Divisionwithatleastoneoperatoroftypedoubleproducestheexpectedresults.doubledivisor,dividend,quotient;divisor=3;dividend=5;quotient=dividend/divisor;quotient=1.6666Resultisthesameifeitherdividendordivisorisoftypeint,Slide2-45,DivisionofIntegers,Becarefulwiththedivisionoperator!int/intproducesanintegerresult(trueforvariablesornumericconstants)intdividend,divisor,quotient;dividend=5;divisor=3;quotient=dividend/divisor;Thevalueofquotientis1,not1.666Integerdivisiondoesnotroundtheresult,thefractionalpartisdiscarded!,Slide2-46,IntegerRemainders,%operatorgivestheremainderfromintegerdivisionintdividend,divisor,remainder;dividend=5;divisor=3;remainder=dividend%divisor;Thevalueofremainderis2,Slide2-47,Display2.5,ArithmeticExpressions,UsespacingtomakeexpressionsreadableWhichiseasiertoread?x+y*zorx+y*zPrecedencerulesforoperatorsarethesameasusedinyouralgebraclassesUseparenthesestoaltertheorderofoperationsx+y*z(yismultipliedbyzfirst)(x+y)*z(xandyareaddedfirst),Slide2-48,Display2.6,OperatorShorthand,SomeexpressionsoccursooftenthatC+containstoshorthandoperatorsforthemAllarithmeticoperatorscanbeusedthisway+=count=count+2;becomescount+=2;*=bonus=bonus*2;becomesbonus*=2;/=time=time/rush_factor;becomestime/=rush_factor;%=remainder=remainder%(cnt1+cnt2);becomesremainder%=(cnt1+cnt2);,Slide2-49,2.4,SimpleFlowofControl,SimpleFlowofControl,FlowofcontrolTheorderinwhichstatementsareexecutedBranchLetsprogramchoosebetweentwoalternatives,Slide2-51,BranchExample,TocalculatehourlywagestherearetwochoicesRegulartime(upto40hours)gross_pay=rate*hours;Overtime(over40hours)gross_pay=rate*40+1.5*rate*(hours-40);Theprogrammustchoosewhichoftheseexpressionstouse,Slide2-52,DesigningtheBranch,Decideif(hours40)istrueIfitistrue,thenusegross_pay=rate*40+1.5*rate*(hours-40);Ifitisnottrue,thenusegross_pay=rate*hours;,Slide2-53,ImplementingtheBranch,if-elsestatementisusedinC+toperformabranchif(hours40)gross_pay=rate*40+1.5*rate*(hours-40);elsegross_pay=rate*hours;,Slide2-54,Display2.7,Display2.8,BooleanExpressions,Booleanexpressionsareexpressionsthatareeithertrueorfalsecomparisonoperatorssuchas(greaterthan)areusedtocomparevariablesand/ornumbers(hours40)Includingtheparentheses,isthebooleanexpressionfromthewagesexampleAfewofthecomparisonoperatorsthatusetwosymbols(Nospacesallowedbetweenthesymbols!)=greaterthanorequalto!=notequalorinequality=equalorequivalent,Slide2-55,Display2.9,if-elseFlowControl(1),if(booleanexpression)truestatementelsefalsestatementWhenthebooleanexpressionistrueOnlythetruestatementisexecutedWhenthebooleanexpressionisfalseOnlythefalsestatementisexecuted,Slide2-56,if-elseFlowControl(2),if(booleanexpression)truestatementselsefalsestatementsWhenthebooleanexpressionistrueOnlythetruestatementsenclosedinareexecutedWhenthebooleanexpressionisfalseOnlythefalsestatementsenclosedinareexecuted,Slide2-57,AND,Booleanexpressionscanbecombinedintomorecomplexexpressionswithcount_down-=1;Output:HelloHelloHellowhencount_downstartsat3,Slide2-65,Display2.11,WhileLoopOperation,First,thebooleanexpressionisevaluatedIffalse,theprogramskipstothelinefollowingthewhileloopIftrue,thebodyoftheloopisexecutedDuringexecution,someitemfromthebooleanexpressionischangedAfterexecutingtheloopbody,thebooleanexpressionischeckedagainrepeatingtheprocessuntiltheexpressionbecomesfalseAwhileloopmightnotexecuteatallifthebooleanexpressionisfalseonthefirstcheck,Slide2-66,whileLoopSyntax,while(booleanexpressionistrue)statementstorepeatSemi-colonsareusedonlytoendthestatementswithintheloopWhile(booleanexpressionistrue)statementtorepeat,Slide2-67,Display2.12,do-whileloop,Avariationofthewhileloop.Ado-whileloopisalwaysexecutedatleastonceThebodyoftheloopisfirstexecutedThebooleanexpressionischeckedafterthebodyhasbeenexecutedSyntax:dostatementstorepeatwhile(boolean_expression);,Slide2-68,Display2.13,Display2.14,Increment/Decrement,Unaryoperatorsrequireonlyoneoperand+infrontofanumbersuchas+5-infrontofanumbersuchas-5+incrementoperatorAdds1tothevalueofavariablex+;isequivalenttox=x+1;-decrementoperatorSubtracts1fromthevalueofavariablex-;isequivalenttox=x1;,Slide2-69,SampleProgram,Bankchargecardbalanceof$502%permonthinterestHowmanymonthswithoutpaymentsbeforeyourbalanceexceeds$100After1month:$50+2%of$50=$51After2months:$51+2%of$51=$52.02After3months:$52.02+2%of$52.02,Slide2-70,Display2.15,InfiniteLoops,LoopsthatneverstopareinfiniteloopsTheloopbodyshouldcontainalinethatwilleventuallycausethebooleanexpressiontobecomefalseExample:Printtheoddnumberslessthan12x=1;while(x!=12)coutxendl;x=x+2;Bettertousethiscomparison:while(x0)cout0?,Slide2-72,2.5,ProgramStyle,ProgramStyle,Aprogramwrittenwithattentiontostyleiseasiertoreadeasiertocorrecteasiertochange,Slide2-74,ProgramStyle-Indenting,ItemsconsideredagroupshouldlooklikeagroupSkiplinesbetweenlogicalgroupsofstatementsIndentstatementswithinstatementsif(x=0)statement;BracescreategroupsIndentwithinbracestomakethegroupclearBracesplacedonseparatelinesareeasiertolocate,Slide2-75,ProgramStyle-Comments,/isthesymbolforasinglelinecommentCommentsareexplanatorynotesfortheprogrammerAlltextonthelinefollowing/isignoredbythecompilerExample:/calculateregularwagesgross_pay=rate*hours;/*and*/enc

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论