




版權(quán)說(shuō)明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
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(“格式說(shuō)明符”,表達(dá)式1,表達(dá)式2,…);
printf(“formatstring”,expr1,expr2,…);
3.2.2FormattedInputandOutputTellsprintf()howtodisplaytheseargumentsArgumentsthatyouwanttodisplayprintf(“Iam%dyearsold\n",age);printf(“%d\n",age);Theformatstringmaycontainbothordinarycharacters
(普通字符)
andconversionspecifications(格式說(shuō)明符:beginwith%
)用格式說(shuō)明符先給要輸出的值占個(gè)位置。輸出時(shí)它會(huì)被要輸出的值替代
Aconversionspecificationisaplaceholderrepresentingavaluetobefilledinduringprinting.%d
isaplaceholderindicatingwherethevalueofi
istobefilledin.inti=3,j=5;printf(“Tomhas%dcats\n",i);printf(“Tomhas%dcatsandIhave%dcats!\n",i,j);Ordinarycharactersareprintedastheyappearinthestring;conversionspecificationsarereplaced.普通字符原樣輸出,格式說(shuō)明符會(huì)被要輸出的值(比如i)替代53.1TheprintfFunction%d–integers按整數(shù)形式輸出%f–floats 按小數(shù)形式輸出%d
worksonlyforint
variables;toprintafloat/double
variable,use%f
instead.Bydefault,
%f
displaysanumberwithsixdigitsafterthedecimalpoint.(%f默認(rèn)輸出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(輸出表達(dá)式的值)ReadingandWritingIntegers八、十六、無(wú)符號(hào)數(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十、八、十六、無(wú)符號(hào)數(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列則左補(bǔ)空格,前面有負(fù)號(hào)則右補(bǔ)空格。如果數(shù)據(jù)本身大于m列,則全部輸出。例%4d,%10f12%04d%d—displayanintegerindecimalform.mindicatestheminimumnumberofdigitstodisplay(extrazerosareaddedtothebeginningofthenumberifnecessary).(例如%04d表示至少輸出4個(gè)數(shù)字,不夠4個(gè)就在前面補(bǔ)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默認(rèn)輸出整數(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”);}選擇機(jī)構(gòu)首先測(cè)試?yán)ㄌ?hào)中的條件,根據(jù)條件成立與否來(lái)選擇對(duì)應(yīng)的語(yǔ)句執(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)系(邏輯)表達(dá)式如果成立,則認(rèn)為該表達(dá)式的值為1(真),不成立則認(rèn)為表達(dá)式的值為0(假)。比如5>3,這個(gè)表達(dá)式的值為143C’srelationaloperators(關(guān)系運(yù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ùn)算符優(yōu)先級(jí)比算術(shù)運(yùn)算符低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||如果左邊的表達(dá)式就可以確定整個(gè)表達(dá)式的值,右邊表達(dá)式不會(huì)被執(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語(yǔ)句嵌套形式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.級(jí)聯(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. 本站所有資源如無(wú)特殊說(shuō)明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒(méi)有圖紙預(yù)覽就沒(méi)有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- pvc輕質(zhì)隔墻施工方案
- 的日記300字左右
- 2025年惠州城市職業(yè)學(xué)院?jiǎn)握新殬I(yè)傾向性測(cè)試題庫(kù)及參考答案
- 2025年共青團(tuán)知識(shí)競(jìng)賽試題(附答案)
- 2025年江西司法警官職業(yè)學(xué)院?jiǎn)握新殬I(yè)適應(yīng)性測(cè)試題庫(kù)帶答案
- 2025年湖南理工職業(yè)技術(shù)學(xué)院?jiǎn)握新殬I(yè)適應(yīng)性測(cè)試題庫(kù)附答案
- 2025年泉州經(jīng)貿(mào)職業(yè)技術(shù)學(xué)院?jiǎn)握新殬I(yè)技能測(cè)試題庫(kù)新版
- 2025年青島港灣職業(yè)技術(shù)學(xué)院?jiǎn)握新殬I(yè)傾向性測(cè)試題庫(kù)參考答案
- 2024-2025學(xué)年高中化學(xué) 第二單元 化學(xué)與資源開(kāi)發(fā)利用 2.3 石油、煤和天然氣的綜合利用教學(xué)實(shí)錄1 新人教版選修2
- 7火山噴發(fā)(教學(xué)設(shè)計(jì))-2023-2024學(xué)年科學(xué)六年級(jí)下冊(cè)人教鄂教版
- 《M公司員工忠誠(chéng)度分析案例報(bào)告》
- 人行吊橋拆除方案
- 工程計(jì)量報(bào)審表
- 湖南省長(zhǎng)沙市各縣區(qū)鄉(xiāng)鎮(zhèn)行政村村莊村名居民村民委員會(huì)明細(xì)及行政區(qū)劃代碼
- 人教版音樂(lè)八年級(jí)下冊(cè)《奧林匹克頌、奧林匹克號(hào)角》課件
- 民族民間音樂(lè)試題
- 2022年河北公務(wù)員考試《申論》真題及參考答案
- 汽車涂裝工藝完整版ppt課件全套教程
- 思想道德與法治課件:第四章 第二節(jié) 社會(huì)主義核心價(jià)值觀的顯著特征
- 十年來(lái)北京蓋了多少住宅
- 超精密加工裝備及其關(guān)鍵部件課件
評(píng)論
0/150
提交評(píng)論