




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quá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)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 佛山建筑改造施工方案
- 統(tǒng)編版(2024)道德與法治七年級下冊第一單元 珍惜青春時光 單元測試卷(含答案)
- 公墓焚燒房施工方案
- 飼養(yǎng)池施工方案
- 中級葡萄酒知識培訓(xùn)課件
- 2025屆浙江省寧波市北侖區(qū)重點達標名校中考生物模擬試卷含解析
- 中國黃金回購合同范例
- 個人獨資出資協(xié)議合同范例
- 學(xué)期安全教育與培訓(xùn)計劃
- 高危地區(qū)保安人員的培訓(xùn)需求計劃
- DL-T+544-2012電力通信運行管理規(guī)程
- 零食門市轉(zhuǎn)讓協(xié)議書范本
- 家庭經(jīng)濟困難學(xué)生認定申請表
- 2024版工程合同變更流程
- 運用PDCA縮短ST段抬高型急性心肌梗死病人在急診停留時間
- 陜西省咸陽彩虹中學(xué)2025年高考數(shù)學(xué)試題模擬卷(1)含解析
- 2023年全省職業(yè)院校技能大賽高職教師組護理技能賽項競賽規(guī)程
- 車庫租賃合同
- 法人不參與經(jīng)營免責協(xié)議
- 小學(xué)生心理健康主題家長會
- QB/T 4031-2024 阻燃性汽車空氣濾紙(正式版)
評論
0/150
提交評論