選擇結(jié)構(gòu)Chapter3SelectionStatements課件培訓(xùn)課件_第1頁
選擇結(jié)構(gòu)Chapter3SelectionStatements課件培訓(xùn)課件_第2頁
選擇結(jié)構(gòu)Chapter3SelectionStatements課件培訓(xùn)課件_第3頁
選擇結(jié)構(gòu)Chapter3SelectionStatements課件培訓(xùn)課件_第4頁
選擇結(jié)構(gòu)Chapter3SelectionStatements課件培訓(xùn)課件_第5頁
已閱讀5頁,還剩45頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

Chapter3SelectionStatements§3.1TheBooleanTypeandOperators§3.2Theif-elseStatements§3.3CaseStudies§3.4LogicalOperators§3.5SwitchStatements§3.6OperatorPrecedenceandAssociativityBoolean(布爾)typeThedatatypewithtwopossiblevalues“true”or“false”boollighton=true;Internalrepresentation“1”->“true”;“0”->“false”cout<<lighton;Anynon-zerovalueistreatedastrueboollighton=-1;cout<<lighton;§3.1TheBooleanTypeandOperators2RelationalOperators(關(guān)系運算符)Alsonamed“Comparison”(比較)operatorsTocomparetwovaluesTheresultisaBooleanvalue3boollighton=(1>2);“?”:theresultvaluedependsonthetruthvalueofaBooleanexpression.Booleanexpression:expressionwithaBooleanvalue(booleanExp)?exp1:exp2y=(x>0)?1:-1;Ifx>0,yisassignedtobe1;Otherwise,yisassignedtobe-1;Conditional(條件)Operator4Sequence:順序Selection(branching):選擇Loop(Iteration):循環(huán)Threecontrolstructures6ifif-elseswitchSelectionStatements7if(BooleanExpression){statement(s);}Simple

ifStatements8if(radius>=0){area=radius*radius*PI;cout<<"Theareaforthecircleof"<<"radius"<<radius<<"is"<<area;}Note9Example:EvenorOdd?10Listing3.1--aprogramthatcheckswhetheranumberisevenorodd.--promptstheusertoenteraninteger(line9)--displays“numberiseven”ifitiseven(lines11-12)and“numberisodd”ifitisodd(lines14-15).TestBooleanAcommonmistake:

Addingasemicolonattheendofanifclause.Caution11Thismistakeishardtofind:Notacompilationerror;Notaruntimeerror;Alogicerror!if(booleanExpression){statement(s)-for-the-true-case;}else{statement(s)-for-the-false-case;}Theif...elseStatement12if(i>k){if(j>k)cout<<"iandjaregreaterthank";}elsecout<<"iislessthanorequaltok";Nested(嵌套)ifStatements13MultipleAlternativeifStatements14Traceif-elsestatement15if(score>=90.0)grade='A';elseif(score>=80.0)grade='B';elseif(score>=70.0)grade='C';elseif(score>=60.0)grade='D';elsegrade='F';Supposescoreis70.0ExittheifstatementTheconditionisfalseTheconditionisfalseTheconditionistruegradeisCTheelseclausematchesthemostrecentifclauseinthesameblock.Dangling(垂懸)“else”16Usebracestomakethematchingclear!}{17DanglingelseNothingisprintedfromtheprecedingstatement.Toforcetheelseclausetomatchthefirstifclause,youmustaddapairofbraces:

inti=1;intj=2;intk=3;if(i>j){if(i>k)cout<<"A";}elsecout<<"B";ThisstatementprintsB.18TipsError1:ForgettingNecessaryBracesError2:WrongSemicolonattheifLineCommonErrorsinSelection19Error3:MistakenlyUsing=for==CommonErrorsinSelection20if(count=1)cout<<"countis1"<<endl;elsecout<<"countisnot1"<<endl;TheProblemofBodyMassIndex(BMI)BMIisameasureofhealthonweight.TheinterpretationofBMIforpeople16yearsorolderisasfollows:§3.3CaseStudies21ComputeBMITheUSfederalpersonalincometaxiscalculatedbasedonthefilingstatusandtaxableincome.Thetaxratesfor2002areshowninTable3.6.Example:ComputingTaxes22if(status==0){//Computetaxforsinglefilers}elseif(status==1){//Computetaxformarriedfilejointly}elseif(status==2){//Computetaxformarriedfileseparately}elseif(status==3){//Computetaxforheadofhousehold}else{//Displaywrongstatus}Example:ComputingTaxes,cont.23ComputeTaxAprogramforafirstgradertopracticesubtractions.Randomlygeneratestwosingle-digitintegersnumber1andnumber2withnumber1>=number2,displaysaquestionsuchas“Whatis9–2?”Thestudenttypestheanswer,Theprogramdisplaysamessagetoindicatewhethertheansweriscorrect.Example:ASimpleMathLearningTool24SubtractionQuizShowtheoutputofthefollowingcode,withthevariablevaluesontheright,respectively.ReviewQuestions25if(x>2)if(y>2){intz=x+y; cout<<"zis"<<z<<endl;}else cout<<"xis"<<x<<endl;x=2,y=3;x=3,y=2;Alsoknownas“Boolean”operatorsTooperateonBooleanvaluestogetanewone§3.4Logical(邏輯)Operators26Operator Name ! not && and || or TruthTable27Listing3.3Example28intnumber;cout<<"Enteraninteger:";cin>>number;cout<<(number%2==0&&number%3==0);cout<<(number%2==0||number%3==0);cout<<((number%2==0||number%3==0)&&!(number%2==0&&number%3==0));TestBooleanOperators&&:

conditionalorshort-circuitANDoperator

p1&&p2C++firstevaluatesp1,ifp1istrue,thenevaluatesp2;ifp1isfalse,itdoesnotevaluatep2.||:conditionalorshort-circuitORoperatorp1||p2C++firstevaluatesp1,ifp1isfalsethenevaluatesp2;ifp1istrue,itdoesnotevaluatep2.Short-Circuit(短路)Operator29Aprogramtojustifywhetheragivenyearitisaleapyear.ThenumberisinputbyuserExample:Leapyear30LeapYear(year%4==0&&year%100!=0)||(year%400==0)AlotterygameAtwo-digitnumberbycomputerrandomlyAtwo-digitnumberbyuserIfthetwonumbersareequal,userwins$10,000Ifthetwodigitsmatch,userwins$3,000Ifoneofthetwodigitsmatches,userwins$1,000Example:Lottery31Lotteryswitch(status){case0:computetaxesforsinglefilers;break;case1:computetaxesformarriedfilejointly;break;case2:computetaxesformarriedfileseparately;break;case3:computetaxesforheadofhousehold;break;default: cout<<"Errors:invalidstatus";}§3.5SwitchStatements32switchStatementFlowChart33switchStatementRules34switch(switch-expression){casevalue1:statement(s)1;break;casevalue2:statement(s)2;break;

…casevalueN:statement(s)N;break;default:statement(s)-for-default;}avalueofintegerenclosedinparentheses.Thecasebranchisexecutedwhenthevalueinthecasestatementmatchesthevalueoftheswitch-expression.value1,...,andvalueNaredifferentconstantexpressionstheycannotcontainvariablesintheexpression,suchas1+x

switchStatementRules35ThedefaultcaseisoptionalItcanbeusedtoperformactionswhennoneofthespecifiedcasesmatchesTheorderofthecases(includingthedefaultcase)doesnotmatter.ThekeywordbreakisoptionalItshouldbeusedattheendofeachcasetoterminatetheremainderoftheswitchstatement.Ifthebreakstatementisnotpresent,thenextcasestatementwillbeexecuted.switch(switch-expression){casevalue1:statement(s)1;break;casevalue2:statement(s)2;break;

…casevalueN:statement(s)N;break;default:statement(s)-for-default;}36Traceswitchstatementswitch(day){

case1://Falltothroughtothenextcase

case2://Falltothroughtothenextcase

case3://Falltothroughtothenextcase

case4://Falltothroughtothenextcase

case5:cout<<"Weekday";break;

case0://Falltothroughtothenextcase

case6:cout<<"Weekend";}Supposedayis3:37Traceswitchstatementswitch(day){

case1://Falltothroughtothenextcase

case2://Falltothroughtothenextcase

case3://Falltothroughtothenextcase

case4://Falltothroughtothenextcase

case5:cout<<"Weekday";break;

case0://Falltothroughtothenextcase

case6:cout<<"Weekend";}Supposedayis3:38Traceswitchstatementswitch(day){

case1://Falltothroughtothenextcase

case2://Falltothroughtothenextcase

case3://Falltothroughtothenextcase

case4://Falltothroughtothenextcase

case5:cout<<"Weekday";break;

case0://Falltothroughtothenextcase

case6:cout<<"Weekend";}Supposedayis3:39Traceswitchstatementswitch(day){

case1://Falltothroughtothenextcase

case2://Falltothroughtothenextcase

case3://Falltothroughtothenextcase

case4://Falltothroughtothenextcase

case5:cout<<"Weekday";break;

case0://Falltothroughtothenextcase

case6:cout<<"Weekend";}Supposedayis3:40Traceswitchstatementswitch(day){

case1://Falltothroughtothenextcase

case2://Falltothroughtothenextcase

case3://Falltothroughtothenextcase

case4://Falltothroughtothenextcase

case5:cout<<"Weekday";break;

case0://Falltothroughtothenextcase

case6:cout<<"Weekend";}Supposedayis3:TraceswitchStatementw/o“break”41cin>>ch;switch(ch){

case'a':cout<<ch;

case'b':cout<<ch;

case'c':cout<<ch;}Nextstatement;Supposechis'a':chis'a':ExecutethislineExecutethislineExecutethislineExecutenextstatementTraceswitchstatement42switch(ch){

case'a':cout<<ch;

break;

case'b':cout<<ch;break;

case'c':cout<<ch;}

Nextstatement;ExecutenextstatementSupposechis'a':chis'a':ExecutethislineExecutethislineGettheyearfromuser,,anddisplaytheanimal.Example:ChineseZodiac43ChineseZodiacWhat’sthevalueofyafterthefollowingcode?ReviewQuestions44x=0;y=1;switch(x+1){ case0:y+=1; case1:y+=2; default:y+=x;}Howtoevaluate3+4*4>5*(4+3)–1?PrecedenceTheprecedencethattheoperatorsare“operated”AssociativityTheorderthatadjacentoperatorswiththesameprecedenceare“operated”

§3.6OperatorPrecedenceand

Associativity45OperatorPrecedencevar++,var--,static_cast()+,-(plusandminus),++var,--var(type)Casting!(Not)*,/,%+,-(additionandsubtraction)<,<=

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論