




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
Chapter3ProgramControlStructure格式化的輸入輸出FANGWANGOutline3.1Statement3.2InputandOutput3.3TheSequenceStructure3.4TheSelectionStructure3.5TheloopStructure23.2.1SingleCharacterInput/OutputReadingandWritingCharactersUsinggetcharandputcharForsingle-characterinputandoutput,getchar
andputcharareanalternativetoscanfandprintf.writesacharacter:
putchar(a);readsonecharacter:
c=getchar();Likescanf,getchardoesn’tskipwhite-spacecharactersasitreads.#include<stdio.h>31.TheprintfFunctionPrintingtheValueofaVariable輸出變量的值Theprintffunctionmustbesuppliedwithaformatstring,followedbyanyvaluesthataretobeinsertedintothestringduringprinting:printf(“格式說明符”,表達式1,表達式2,…);
printf(“formatstring”,expr1,expr2,…);
3.2.2FormattedInputandOutputTellsprintf()howtodisplaytheseargumentsArgumentsthatyouwanttodisplayprintf(“Iam%dyearsold\n",age);printf(“%d\n",age);Theformatstringmaycontainbothordinarycharacters
(普通字符)
andconversionspecifications(格式說明符:beginwith%
)用格式說明符先給要輸出的值占個位置。輸出時它會被要輸出的值替代
Aconversionspecificationisaplaceholderrepresentingavaluetobefilledinduringprinting.%d
isaplaceholderindicatingwherethevalueofi
istobefilledin.inti=3,j=5;printf(“Tomhas%dcats\n",i);printf(“Tomhas%dcatsandIhave%dcats!\n",i,j);Ordinarycharactersareprintedastheyappearinthestring;conversionspecificationsarereplaced.普通字符原樣輸出,格式說明符會被要輸出的值(比如i)替代53.1TheprintfFunction%d–integers按整數(shù)形式輸出%f–floats 按小數(shù)形式輸出%d
worksonlyforint
variables;toprintafloat/double
variable,use%f
instead.Bydefault,
%f
displaysanumberwithsixdigitsafterthedecimalpoint.(%f默認輸出6位小數(shù))6PrintingtheValueofaVariable7Example:inti;doublex;i=10; x=43.2892;
printf("i=%d,x=%f\n",i,x);Output:i=10,x=43.289200Classexercise4:outputCreateanewprojectnamed“ex04”declareavariabletostore3andanothervariabletostore1.3.display2variablesandseparatethemwithaspace.Thefilenamedoesn’tmatter,butdon’tusespace.89printf
candisplaythevalueofanynumericexpression.volume=height*length*width;
Thestatementsprintf("%d\n",volume);couldbereplacedbyprintf("%d\n",height*length*width);printf("%d\n",833+5);printf("%f\n",8.33);PrintingExpressions(輸出表達式的值)ReadingandWritingIntegers八、十六、無符號數(shù)輸入輸出格式符Readingandwritingunsigned,short,andlongintegersrequiresnewconversionspecifiers.Whenreadingorwritinganunsignedinteger,usetheletteru,o,x
insteadofdintheconversionspecification.
%u%o%x
unsignedintu;
scanf("%u",&u);/*readsuinbase10*/ printf("%u",u);/*writesuinbase10*/ scanf("%o",&u);/*readsuinbase8*/ printf("%o",u);/*writesuinbase8*/ scanf("%x",&u);/*readsuinbase16*/ printf("%x",u);/*writesuinbase16*/10ReadingandWritingIntegers十、八、十六、無符號數(shù)輸入輸出格式符Whenreadingorwritingashortinteger,puttheletterhinfrontofd,o,u,orx:%hd%ho%hu%hx
shorts;
scanf("%hd",&s); printf("%hd",s);Whenreadingorwritingalonginteger,puttheletterl
infrontofd,o,u,orx.%ld%lo%lu%lxWhenreadingorwritingalong
long
integer(C99only),putthelettersllinfrontofd,o,u,orx.113.1TheprintfFunctionTheminimumfieldwidth,m,specifiestheminimumnumberofcharacterstoprint.Ifthevaluetobeprintedrequiresfewerthanmcharacters,itisright-justifiedwithinthefield.%4ddisplaysthenumber123as?123.(?representsthespacecharacter.)Puttingaminussigninfrontofmcausesleftjustification.Thespecification%-4dwoulddisplay123as123?.Ifthevaluetobeprintedrequiresmorethanmcharacters,thefieldwidthautomaticallyexpandstothenecessarysize.m是最小輸出寬度,不足m列則左補空格,前面有負號則右補空格。如果數(shù)據(jù)本身大于m列,則全部輸出。例%4d,%10f12%04d%d—displayanintegerindecimalform.mindicatestheminimumnumberofdigitstodisplay(extrazerosareaddedtothebeginningofthenumberifnecessary).(例如%04d表示至少輸出4個數(shù)字,不夠4個就在前面補0)inti=123;printf("%04d\n",i);output0123133.1TheprintfFunctionConversionSpecificationsAconversionspecificationcanhavetheform%m.pXor%-m.pX,wheremandpareintegerconstantsandXisaletter.E.g:%10.2f,mis10,pis2,andXisf.Bothmandpareoptional;Inthespecification%10f,mis10andp(alongwiththeperiod)ismissing,butinthespecification%.2f,pis2andmismissing.143.1TheprintfFunctionConversionSpecificationsThemeaningoftheprecision,
p,dependsonthechoiceofX,theconversionspecifier.Toforce%f
todisplaypdigitsafterthedecimalpoint,put.p
between
%
andf.(%.2f表示整數(shù)部分原樣輸出,小數(shù)部分則輸出前兩位,%f默認輸出整數(shù)和6位小數(shù)
)
doubleProfit=2150.4812;
printf("Profit:%.2f\n",profit); OutputProfit:2150.48 printf("Profit:%f\n",profit); OutputProfit:2150.48120015Classexercise5:inputandoutputCreateanewprojectnamed“ex05”DeclareavariabletostorePI(πtheratioofacircle'scircumferencetoitsdiameter:3.1415926535)andthendisplayitwith3digitsafterthedecimalpoint.Thefilenamedoesn’tmatter,butdon’tusespace.16%m.pf(m.p最小寬度.精度)%10.2fdoubleProfit=2150.4812;printf("Profit:%10.2f\n",profit);Output
Profit:2150.48
173.1TheprintfFunctionConversionspecifiersforfloating-pointnumbers: %e
—Exponentialformat.pindicateshowmanydigitsshouldappearafterthedecimalpoint(thedefaultis6).Ifpis0,nodecimalpointisdisplayed.(按指數(shù)形式輸出) %g
—Eitherexponentialformatorfixeddecimalformat,dependingonthenumber’ssize.pindicatesthemaximumnumberofsignificantdigitstobedisplayed.Thegconversionwon’tshowtrailingzeros.Ifthenumberhasnodigitsafterthedecimalpoint,gdoesn’tdisplaythedecimalpoint.183.1TheprintfFunctionEscapeSequences轉(zhuǎn)義字符The\ncodethatusedinformatstringsiscalledanescapesequence.Escapesequencesenablestringstocontainnonprinting(control)charactersandcharactersthathaveaspecialmeaning(suchas").Apartiallistofescapesequences:Alert(bell) \acausesanaudiblebeeponmostmachine響鈴Backspace \bmovesthecursorbackoneposition退格Newline \nadvancesthecursortothebeginningofthenextlineHorizontaltab\tmovesthecursortothenexttabstop1920\t:A
horizontaltabisalways8spaces(positions).Itisusedtocreatethetabspaces.3.1TheprintfFunctionEscapeSequencesAnothercommonescapesequenceis\",whichrepresentsthe"character: printf("\"Hello!\""); /*prints"Hello!"*/Toprintasingle\character,puttwo\charactersinthestring:
printf("\\"); /*printsone\character*/213.2ThescanfFunction輸入函數(shù)scanf
istheClibrary’scounterparttoprintf.scanfrequiresaformatstringtospecifytheappearanceoftheinputdata.Exampleofusingscanftoreadanintvalue: scanf("%d",&a);/*readsaninteger;storesintoa*/The&
symbolisusually(butnotalways)requiredwhenusingscanf.Readingafloatvaluerequiresaslightlydifferentcallofscanf: scanf("%f",&x);"%f"tellsscanftolookforaninputvalueinfloatformat(thenumbermaycontainadecimalpoint,butdoesn’thaveto).doublez;scanf("%lf",&z);22Classexercise6:inputCreateanewprojectnamed“ex06”Declareavariable“age”andenteryouragethendisplayit.233.2ThescanfFunction輸入函數(shù)scanfreadsinputaccordingtoaparticularformat.Ascanfformatstringmaycontainbothordinarycharactersandconversionspecifications.Inmanycases,ascanfformatstringwillcontainonlyconversionspecifications: inti,j; doublex,y;
scanf("%d%d%lf%lf",&i,&j,&x,&y);24Formatstringtellsscanf()howtheinputisformattedspecifytheappearanceoftheinputdataArgumentsareaddressofvariablesthatwillstorethevalueread3.2ThescanfFunction inti,j; doublex,y;
scanf("%d%d%lf%lf",&i,&j,&x,&y);Sampleinput: 1-20.3-4.0e3 scanfwillassign1,–20,0.3,and–4000.0toi,j,x,andy,respectively.253.2ThescanfFunctionHowscanfWorksAsitsearchesforanumber,scanfignoreswhite-spacecharacters(space,tab,andnew-line用空格,制表符,換行分隔).Acallofscanfthatreadsfournumbers: scanf("%d%d%lf%lf",&i,&j,&x,&y);Thenumberscanbeononelineorspreadoverseverallines:
1 -20.3 -4.0e3scanfseesastreamofcharacters(¤representsnew-line): ??1¤-20???.3¤???-4.0e3¤ ssrsrrrsssrrssssrrrrrr(s=skipped;r=read)scanf“peeks”atthefinalnew-linewithoutreadingit.263.2ThescanfFunctiontheprogrammermustcheckthatthenumberofconversionspecificationsmatchesthenumberofinputvariablesandthateachconversionisappropriateforthecorrespondingvariable.Anothertrapinvolvesthe&symbol,whichnormallyprecedeseachvariableinascanfcall.The&isusually(butnotalways)required,andit’stheprogrammer’sresponsibilitytoremembertouseit.27Classexercise7:inputCreateanewprojectnamed“ex07”declare4variables:Math,English,Computerasdoubletype;Enteryourmarkofthemandoutputthesumandtheaverage.28Classexercise8:inputCreateanewprojectnamed“ex08”declare4variables:volume,height,length,width;Computethevolumeofthisboxanddisplayit.29Howtowriteaprogram?Step1:declarevariablesStep2:inputdataStep3:calculateStep4:outputwhichdatatypetodeclaredependsonthesizeofthevalueforavariableyouneed.GetroomsStoredataCalculatePrinttheresult2.ThescanfFunctionOrdinaryCharactersinFormatStringsInputmustmatchtheformatstringExamples:Iftheformatstringis"%d/%d"andtheinputis3/5,scanf
succeeds.Iftheinputis35,scanffails,becausethe/intheformatstringdoesn’tmatchthespaceintheinput.
scanf("%d,%d",&i,&j);input:3,531NOJquestion2DateClassexercise9:#include<stdio.h>#include<stdlib.h>intmain(){intmonth,day,year;scanf("%d/%d/%d",&month,&day,&year);printf("%04d%02d%02d\n",year,month,day);return0;}Step1:declarevariablesStep2:inputdataStep3:output3.2ThescanfFunctionConfusingprintfwithscanfPuttinganew-linecharacterattheendofascanfformatstringisusuallyabadidea.Toscanf,anew-linecharacterinaformatstringisequivalenttoaspace;bothcausescanftoadvancetothenextnon-white-spacecharacter.Iftheformatstringis"%d\n",scanfwillskipwhitespace,readaninteger,thenskiptothenextnon-white-spacecharacter.Aformatstringlikethiscancauseaninteractiveprogramto“hang.”343.3TheSequenceStructureThesequencestructureTheselectionstructureTheloopstructure35Program
Control
Structures3typesoflogicstructuresinprogramming:SequencestructureSelectionstructureLoopstructureCControlLoopStatement1Statement2Statement3StatementnStatement1Statement23.4SelectionStatements選擇結(jié)構(gòu)
Aconditionalflowstatementisamechanismthatallowsyoutobranchyourprogramflowinoneormoredirectionsbasedontheresultofacertaintestif(a>b){printf(“a”);}else{printf(“b”);}選擇機構(gòu)首先測試括號中的條件,根據(jù)條件成立與否來選擇對應的語句執(zhí)行。41Statement1Statement2Classexercise9:whoiselderCreateanewprojectnamed“ex09”declare2variables:mom,dad;Inputtheirages;Comparetheiragesandprintwhoiselder.423.4.1RelationalExpressionsSeveralofC’sstatementsmusttestthevalueofanexpressiontoseeifitis“true”or“false.”Forexample,anifstatementmightneedtotesttheexpressiona>b;atruevaluewouldindicatethataisgreaterthanb.InC,acomparisonsuchasa>byieldsaninteger:either0(false)or1(true).關(guān)系(邏輯)表達式如果成立,則認為該表達式的值為1(真),不成立則認為表達式的值為0(假)。比如5>3,這個表達式的值為143C’srelationaloperators(關(guān)系運算符) < lessthan > greaterthan <= lessthanorequalto >= greaterthanorequaltoTheseoperatorsproduce0(false)or1(true)whenusedinexpressions.
inta=1,b=2; printf(“%d\n”,a>b); output:0
floata=3.14,b=9.8; printf(“%d\n”,a<b); output:144LogicalExpressionsRelationalOperatorsTheprecedenceoftherelationaloperatorsislowerthanthatofthearithmeticoperators.Forexample,a+b
<
c
+
dmeans(a
+
b)
<
(c
+
d).Therelationaloperatorsareleftassociative.關(guān)系運算符優(yōu)先級比算術(shù)運算符低45LogicalExpressions == equalto != notequaltoTheequalityoperatorsareleftassociativeandproduceeither0(false)or1(true)astheirresult.Theequalityoperatorshavelowerprecedencethantherelationaloperators,sotheexpression
a<b==a<b isequivalentto
(a<b)==(a<b)46RelationalOperatorsTheexpression a<b<cislegal,butdoesnottestwhetherjliesbetweeniandk.Sincethe<operatorisleftassociative,thisexpressionisequivalentto (a<b)<cThe1or0producedbyi
<
jisthencomparedtok.Thecorrectexpressionisi
<
j
&&
j
<
k.Howabout5>3>2473.4.1LogicalExpressionsLogicalOperatorsMorecomplicatedlogicalexpressionscanbebuiltfromsimpleronesbyusingthelogicaloperators:
! logicalnegation非 && logicaland與 || logicalor或The!operatorisunary,while&&and||arebinary.Thelogicaloperatorsproduce0or1astheirresult.48LogicalOperatorsThe!operatorhasthesameprecedenceastheunaryplusandminusoperators.Theprecedenceof&&and||islowerthanthatoftherelationalandequalityoperators.Forexample,a
<
b
&&
x==
ymeans(a
<
b)
&&
(x
==
y).The!operatorisrightassociative;&&and||areleftassociative.49Classexercise10:question7leapyear①Anyyearthatisevenlydivisibleby4butnotevenlydivisibleby100isaleapyeary%4==0&&y%100!=0Or②Anyyearthatisevenlydivisibleby400isaleapyeary%400==0inty;scanf("%d",&y);if(y%400==0||(y%4==0&&y%100!=0))printf("Yes\n");elseprintf("No\n");
LogicalOperators!expr
hasthevalue1ifexprhasthevalue0.expr1&&expr2
hasthevalue1ifthevaluesofexpr1
andexpr2arebothnonzero.expr1||expr2
hasthevalue1ifeitherexpr1orexpr2(orboth)hasanonzerovalue.Inallothercases,theseoperatorsproducethevalue0.Thelogicaloperatorstreatanynonzerooperandasatruevalueandanyzerooperandasafalsevalue.0為假,非0為真53LogicalOperatorsBoth&&and||perform“short-circuit”evaluation:theyfirstevaluatetheleftoperand,thentherightone.Ifthevalueoftheexpressioncanbededucedfromtheleftoperandalone,therightoperandisn’tevaluated.Example: (i!=0)&&(j>0) (i!=
0)isevaluatedfirst.Ifiisn’tequalto0,then(j
>
0)isevaluated.Ifiis0,theentireexpressionmustbefalse,sothere’snoneedtoevaluate(j
>
0).&&and||如果左邊的表達式就可以確定整個表達式的值,右邊表達式不會被執(zhí)行。54LogicalExpressionsLogicalOperatorstheshort-circuitnatureofthe&&and||
Example:
i>0&&++j>0
Ifi
>
0isfalse,then++j
>
0isnotevaluated,sojisn’tincremented.example: v1=v2=2; n1=1;n2=2;n3=3;n4=4;t=(v1=n1>n2)&&(v2=n3>n4) v1=?v2=?553.4.3TheifStatementTheifstatementallowsaprogramtochoosebetweentwoalternativesbytestinganexpression.Initssimplestform,theifstatementhastheform
if(expression)
statementWhenanifstatementisexecuted,expressionisevaluated;ifitsvalueisnonzero
(orture),statementisexecuted.Example: if(line_num==MAX_LINES) line_num=0;5657E.g1:inputaninterger,ifitispositivethendisplayit
intmain(){intx;scanf(”%d”,&x);if(x>0)printf(”%d\n”,x);return0;}Classexercise11:PositivenumberTheifStatementConfusing==(equality)with=(assignment)isperhapsthemostcommonCprogrammingerror.Thestatement
if(i==0)… testswhetheriisequalto0.Thestatement if(i=0)… assigns0toi,thentestswhethertheresultisnonzero.58TheifStatementOftentheexpressioninanifstatementwilltestwhetheravariablefallswithinarangeofvalues.Totestwhether0£
i<n:
if(0<=i&&i<n)…Totesttheoppositecondition(iisoutsidetherange):
if(i<0||i>=n)…59TheifStatementCompoundStatementsIntheifstatementtemplate,noticethatstatementissingular,notplural:
if(expression)statementTomakeanifstatementcontroltwoormorestatements,useacompoundstatement.Acompoundstatementhastheform
if(expression)
{statements}Puttingbracesaroundagroupofstatementsforcesthecompilertotreatitasasinglestatement.60TheifStatement61CompoundStatementsExample: if(expression) {line_num=0;page_num++;}Acompoundstatementisusuallyputonmultiplelines,withonestatementperline: if(expression){ line_num=0; page_num++; }Eachinnerstatementstillendswithasemicolon,butthecompoundstatementitselfdoesnot.TheifStatementCompoundStatementsExampleofacompoundstatementusedinsideanifstatement: if(line_num==MAX_LINES){ line_num=0; page_num++;
}62E.g2:inputthevaluesofaandb,comparethem,ifaislessthanb,thenswaptheirvalues.63
intmain(){doublea,b,t;scanf(”%lf%lf”,&a,&b);if(a<b){t=a;a=b;b=t;}//Swaptheirvaluesprintf(”%fisgreaterthan%f\n”,a,b);return0;}TheifStatementTheelseClauseAnifstatementmayhaveanelseclause: if(expression)statement
elsestatementThestatementthatfollowsthewordelseisexecutediftheexpressionhasthevalue0.Example:if(a>b)max=a; elsemax=b;64TheifStatementTheelseClauseWhenanifstatementcontainsanelseclause,whereshouldtheelsebeplaced?ManyCprogrammersalignitwiththeifatthebeginningofthestatement.Innerstatementsareusuallyindented,butifthey’reshorttheycanbeputonthesamelineastheifandelse: if(a>b)max=a; elsemax=b;656666
#include<stdio.h>#include<math.h>intmain(){doublex,y;scanf(”%lf”,&x);if(x>=0)y=x;elsey=x*x*x-1.0;printf(”y=%f\n”,y); return0;}xx≥0x3-1x<0Classexercise12:piecewisefunction--enterxandcomputeyy=Declarevariablesx,yInputxCalculateyDisplayy#include<math.h>pow(a,b);67Classexercise13:Heron‘sformulaTocalculatetheareaofatriangleusingHeron'sformula,youneedtoknowthelengthsofallthreesidesofthetriangle.Inputthelengthof3sides,calculatetrianglearea.Ifyoucan’tmakeatrianglewiththem,display“ERROR”.Declarevariablea,b,cInput3sidesDetermineif3sidelengthscanmakeatriangleIfyes,calculatetheareaandoutputitIfnot,display“ERROR”.Hint:sqrt(2)#include<math.h>Trap:1/2is0Todetermineif3sidelengthscanformatriangle,usethetriangleinequalitytheorem,whichstatesthatthesumof2sidesofatrianglemustbegreaterthanthethirdside.Therefore,allyouhavetodoisaddtogethereachcombinationof2sidestoseeifit'sgreaterthanthethirdside.68#include<stdio.h>#include<math.h>intmain(){doublea,b,c,s,area;scanf(”%lf%lf%lf”,&a,&b,&c);if(a+b>c&&a+c>b&&b+c>a)
{
s=(a+b+c)/2.0;area=sqrt(s*(s-a)*(s-b)*(s-c));printf(”area=%8.3f\n”,area);}elseprintf(”ERROR\n”);}TheifStatement69It’snotunusualforifstatementstobenestedinsideotherifstatements:
if(i>j)
if(i>k) max=i; else max=k;
else
if(j>k) max=j; else max=k;Aligningeachelsewiththematchingifmakesthenestingeasiertosee.If語句嵌套形式TheifStatementTheelseClauseToavoidconfusion,pleaseaddbraces:
if(i>j)
{ if(i>k) max=i; else max=k;
}
else
{ if(j>k) max=j; else max=k;
}70TheifStatement71TheelseClauseSomeprogrammersuseasmanybracesaspossibleinsideifstatements: if(i>j){ if(i>k){max=i;}
else{max=k;} }else{ if(j>k){max=j;}
else{max=k; } }TheifStatementThe“Danglingelse”ProblemWhenifstatementsarenested,the“danglingelse”problemmayoccur: if(y!=0) if(x!=0) result=x/y; else printf("Error:yisequalto0\n");Theindentationsuggeststhattheelseclausebelongstotheouterifstatement.However,Cfollowstherulethatanelseclausebelongstothenearestifstatementthathasn’talreadybeenpairedwithanelse.72TheifStatementThe“Danglingelse”ProblemTomaketheelseclausepartoftheouterifstatement,wecanenclosetheinnerifstatementinbraces: if(y!=0){ if(x!=0) result=x/y; }else printf("Error:yisequalto0\n");Usingbracesintheoriginalifstatementwouldhaveavoidedtheprobleminthefirstplace.73Classexercise13-2:question7FindthebiggestnumberTheifStatementTheelseClauseAdvantagesofusingbracesevenwhenthey’renotrequired:Makesprogramseasiertomodify,becausemorestatementscaneasilybeaddedtoanyiforelseclause.Helpsavoiderrorsthatcanresultfromforgettingtousebraceswhenaddingstatementstoaniforelseclause.75TheifStatementCascadedifStatementsA“cascaded”ifstatementisoftenthebestwaytotestaseriesofconditions,stoppingassoonasoneofthemistrue.級聯(lián)式CascadedifStatements
if(expression1)
statement1
elseif(expression2)
statement2 …
elseif(expression3)
statement3
else
statement476TheifStatementCascadedifStatementsExample:
if(n>0) printf(“nispostive\n");
elseif(n==0) printf("nis0\n");
else printf("nisnegative\n");77Classexercise14:lowercase&uppercaseDeclareavariableofchartype.·Readacharacterusinggetchar().·Ifitislowercase,thenconvertittouppercase:a--A.·Ifitisuppercase,thenconvertittolowercase:A--a.·Displaythischaracterusingputchar().78Classexercise15:GradeInputyourgrade,ifit’s4,display“Excellent”……..(cascadedif
)grade:4 Excellent 3 Good 2 Average 1 Poor 0 Failing other Illegalgrade79Acascadedifstatementcanbeusedtocompareanexpressionagainstaseriesofvalues: if(grade==4) printf("Excellent"); elseif(grade==3) printf("Good"); elseif(grade==2) printf("Average"); elseif(grade==1) printf("Poor"); elseif(grade==0) printf("Failing"); else printf("Illegalgrade");
Question15-2:Howmanydigitsscanf("%d",&a);if(0<a&&a<=9) printf("1\n"); elseif(a<=99)printf("2\n");elseif(a<=999)printf("3\n",a);8282#include’’stdio.h”intmain(){intg;printf(”Enterscore:”);scanf(”%d”,&g);if(g<0||g>100)printf(”INPUTERROR!”);elseif(g>=80)printf(”A”);elseif(g>=70)printf(”B”);elseif(g>=60)printf(”C”);elseprintf(”D”);return0;}80~100分A檔70~79分B檔60~69分C檔0~59分D檔TheswitchStatementAcascadedifstatementcanbeusedtocompareanexpressionagainstaseriesofvalues: if(grade==4) printf("Excellent"); elseif(grade==3) printf("Good"); elseif(grade==2) printf("Average"); elseif(grade==1) printf("Poor"); elseif(grade==0) printf("Failing"); else printf("Illegalgrade");
83TheswitchStatementTheswitchstatementisanalternative: switch(grade){ case4:printf("Excellent"); case3:printf("Good"); case2:printf("Average"); case1:printf("Poor"); case0:printf("Failing"); default:printf("Illegalgrade"); //Whenvalueofexpressiondoesn'tmatchwithanycase }84 switch(grade){ case4:printf("Excellent");
break; case3:printf("Good");
break; case2:printf("Average");
break; case1:printf("Poor");
break; case0:printf("Failing");
break; default:printf("Illegalgrade");
break; }Classexercise16:dayDeclareintvariable–dayInputday(1,2,3….)Outputwhat
day
of
the
weekitis85switch
(day)
{
case
1:
printf(“1:MONDAY\n”);
break;
case
2:
printf("2:TUESDAY\n”);break;
case
3:
printf(“3:WEDNESDAY\n”);
break;
case
4:
printf("4:THURSDAY\n”);
break;
case
5:
printf("5:FRIDAY\n”);
break;
case
6:
printf("6:SATURDAY\n”);
break;
case
7:printf("7:SUNDAY\n”);break;
default:
printf("other:INVALIDINPUT\n”);break;
}1:
MONDAY
2:
TUESDAY3:
WEDNESDAY4:
THURSDAY;
5:
FRIDAY6:
SATURDAY7:
SUNDAYother: INVALIDINPUTTheswitchStatementAswitchstatementmaybeeasiertoreadthanacascadedifstatement.switchstatementsareoftenfasterthanifstatements.Mostcommonformoftheswitchstatement: switch(expression){ caseconstant-expression:statements … case
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 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. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 廚房肉類采購合同范本
- 農(nóng)村租房合同范本個人
- 餐飲行業(yè)購銷合同范本
- 雙以上合同范本
- 合同范本五金
- 勞務分包長期合同范本
- 民間個人借款居間服務合同范本
- 吊車租貨合同范本
- 合資購車協(xié)議合同范例
- 啟用合同范例公告
- 統(tǒng)編版五年級下冊道德與法治全冊優(yōu)秀課件
- 湘雅五醫(yī)院-建筑方案設(shè)計課件
- 《教育管理學》課件
- 凈水設(shè)備技術(shù)參數(shù)要求
- 《M公司員工忠誠度分析案例報告》
- 工程計量報審表
- 腦血管造影護理課件
- 被執(zhí)行人財產(chǎn)申報表
- 課題申報講座課件
- 系統(tǒng)科學與系統(tǒng)工程的理論基礎(chǔ)
- 四步創(chuàng)業(yè)法:創(chuàng)業(yè)必備知識點課件
評論
0/150
提交評論