java语言程序设计-基础篇课件(第4章)英文_第1页
java语言程序设计-基础篇课件(第4章)英文_第2页
java语言程序设计-基础篇课件(第4章)英文_第3页
java语言程序设计-基础篇课件(第4章)英文_第4页
java语言程序设计-基础篇课件(第4章)英文_第5页
已阅读5页,还剩91页未读 继续免费阅读

下载本文档

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

文档简介

Chapter4Loops1Chapter4Loops11MotivationsSupposethatyouneedtoprintastring(e.g.,"WelcometoJava!")ahundredtimes.Itwouldbetedioustohavetowritethefollowingstatementahundredtimes:System.out.println("WelcometoJava!");So,howdoyousolvethisproblem?2MotivationsSupposethatyoune2OpeningProblemProblem:3System.out.println("WelcometoJava!");System.out.println("WelcometoJava!");System.out.println("WelcometoJava!");System.out.println("WelcometoJava!");System.out.println("WelcometoJava!");System.out.println("WelcometoJava!");…

System.out.println("WelcometoJava!");System.out.println("WelcometoJava!");System.out.println("WelcometoJava!");100timesOpeningProblemProblem:3System3IntroducingwhileLoops4intcount=0;while(count<100){System.out.println("WelcometoJava");count++;}IntroducingwhileLoops4intco4Objectives5Towriteprogramsforexecutingstatementsrepeatedlyusingawhileloop(§4.2).TodevelopaprogramforGuessNumberandSubtractionQuizLoop(§4.2.1).Tofollowtheloopdesignstrategytodeveloploops(§4.2.2).TodevelopaprogramforSubtractionQuizLoop(§4.2.3).Tocontrolaloopwithasentinelvalue(§4.2.3).Toobtainlargeinputfromafileusinginputredirectionratherthantypingfromthekeyboard(§4.2.4).Towriteloopsusingdo-whilestatements(§4.3).Towriteloopsusingforstatements(§4.4).Todiscoverthesimilaritiesanddifferencesofthreetypesofloopstatements(§4.5).Towritenestedloops(§4.6).Tolearnthetechniquesforminimizingnumericalerrors(§4.7).Tolearnloopsfromavarietyofexamples(GCD,FutureTuition,MonteCarloSimulation)(§4.8).Toimplementprogramcontrolwithbreakandcontinue(§4.9).(GUI)Tocontrolaloopwithaconfirmationdialog(§4.10).Objectives5Towriteprogramsf5whileLoopFlowChart6while(loop-continuation-condition){//loop-body;Statement(s);}intcount=0;while(count<100){System.out.println("WelcometoJava!");count++;}whileLoopFlowChart6while(l6TracewhileLoop7intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}InitializecountanimationTracewhileLoop7intcount=07TracewhileLoop,cont.8intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}(count<2)istrueanimationTracewhileLoop,cont.8intco8TracewhileLoop,cont.9intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}PrintWelcometoJavaanimationTracewhileLoop,cont.9intco9TracewhileLoop,cont.10intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}Increasecountby1countis1nowanimationTracewhileLoop,cont.10intc10TracewhileLoop,cont.11intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}(count<2)isstilltruesincecountis1animationTracewhileLoop,cont.11intc11TracewhileLoop,cont.12intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}PrintWelcometoJavaanimationTracewhileLoop,cont.12intc12TracewhileLoop,cont.13intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}Increasecountby1countis2nowanimationTracewhileLoop,cont.13intc13TracewhileLoop,cont.14intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}(count<2)isfalsesincecountis2nowanimationTracewhileLoop,cont.14intc14TracewhileLoop15intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}Theloopexits.Executethenextstatementaftertheloop.animationTracewhileLoop15intcount=15Problem:GuessingNumbers

Writeaprogramthatrandomlygeneratesanintegerbetween0and100,inclusive.Theprogrampromptstheusertoenteranumbercontinuouslyuntilthenumbermatchestherandomlygeneratednumber.Foreachuserinput,theprogramtellstheuserwhethertheinputistoolowortoohigh,sotheusercanchoosethenextinputintelligently.Hereisasamplerun:16GuessNumberOneTimeGuessNumberProblem:GuessingNumbersWrit16Problem:AnAdvancedMathLearningTool

TheMathsubtractionlearningtoolprogramgeneratesjustonequestionforeachrun.Youcanusealooptogeneratequestionsrepeatedly.Thisexamplegivesaprogramthatgeneratesfivequestionsandreportsthenumberofthecorrectanswersafterastudentanswersallfivequestions.17SubtractionQuizLoopProblem:AnAdvancedMathLear17EndingaLoopwithaSentinelValueOftenthenumberoftimesaloopisexecutedisnotpredetermined.Youmayuseaninputvaluetosignifytheendoftheloop.Suchavalueisknownasasentinelvalue.Writeaprogramthatreadsandcalculatesthesumofanunspecifiednumberofintegers.Theinput0signifiestheendoftheinput.18SentinelValueEndingaLoopwithaSentinel18CautionDon’tusefloating-pointvaluesforequalitycheckinginaloopcontrol.Sincefloating-pointvaluesareapproximationsforsomevalues,usingthemcouldresultinimprecisecountervaluesandinaccurateresults.Considerthefollowingcodeforcomputing1+0.9+0.8+...+0.1:doubleitem=1;doublesum=0;while(item!=0){//Noguaranteeitemwillbe0sum+=item;item-=0.1;}System.out.println(sum);Variableitemstartswith1andisreducedby0.1everytimetheloopbodyisexecuted.Theloopshouldterminatewhenitembecomes0.However,thereisnoguaranteethatitemwillbeexactly0,becausethefloating-pointarithmeticisapproximated.ThisloopseemsOKonthesurface,butitisactuallyaninfiniteloop.19CautionDon’tusefloating-poin19do-whileLoop20do{//Loopbody;Statement(s);}while(loop-continuation-condition);do-whileLoop20do{20forLoopsfor(initial-action;loop-continuation-condition;action-after-each-iteration){//loopbody;Statement(s);}21inti;for(i=0;i<100;i++){ System.out.println("WelcometoJava!");}forLoopsfor(initial-action;21TraceforLoop22inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}DeclareianimationTraceforLoop22inti;Declare22TraceforLoop,cont.23inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}Executeinitializeriisnow0animationTraceforLoop,cont.23inti;E23TraceforLoop,cont.24inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}(i<2)istruesinceiis0animationTraceforLoop,cont.24inti;(24TraceforLoop,cont.25inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}PrintWelcometoJavaanimationTraceforLoop,cont.25inti;P25TraceforLoop,cont.26inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}Executeadjustmentstatementinowis1animationTraceforLoop,cont.26inti;E26TraceforLoop,cont.27inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}(i<2)isstilltruesinceiis1animationTraceforLoop,cont.27inti;(27TraceforLoop,cont.28inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}PrintWelcometoJavaanimationTraceforLoop,cont.28inti;P28TraceforLoop,cont.29inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}Executeadjustmentstatementinowis2animationTraceforLoop,cont.29inti;E29TraceforLoop,cont.30inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}(i<2)isfalsesinceiis2animationTraceforLoop,cont.30inti;(30TraceforLoop,cont.31inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}Exittheloop.ExecutethenextstatementaftertheloopanimationTraceforLoop,cont.31inti;E31Note32Theinitial-actioninaforloopcanbealistofzeroormorecomma-separatedexpressions.Theaction-after-each-iterationinaforloopcanbealistofzeroormorecomma-separatedstatements.Therefore,thefollowingtwoforloopsarecorrect.Theyarerarelyusedinpractice,however.for(inti=1;i<100;System.out.println(i++));

for(inti=0,j=0;(i+j<10);i++,j++){//Dosomething}

Note32Theinitial-actionina32Note33Iftheloop-continuation-conditioninaforloopisomitted,itisimplicitlytrue.Thusthestatementgivenbelowin(a),whichisaninfiniteloop,iscorrect.Nevertheless,itisbettertousetheequivalentloopin(b)toavoidconfusion:Note33Iftheloop-continuation33CautionAddingasemicolonattheendoftheforclausebeforetheloopbodyisacommonmistake,asshownbelow:34LogicErrorfor(inti=0;i<10;i++);{System.out.println("iis"+i);}CautionAddingasemicolonatt34Caution,cont.Similarly,thefollowingloopisalsowrong:inti=0;while(i<10);{System.out.println("iis"+i);i++;}Inthecaseofthedoloop,i=0;do{System.out.println("iis"+i);i++;}while(i<10);35LogicErrorCorrectCaution,cont.Similarly,thef35WhichLooptoUse?36Thethreeformsofloopstatements,while,do-while,andfor,areexpressivelyequivalent;thatis,youcanwritealoopinanyofthesethreeforms.Forexample,awhileloopin(a)inthefollowingfigurecanalwaysbeconvertedintothefollowingforloopin(b):Aforloopin(a)inthefollowingfigurecangenerallybeconvertedintothefollowingwhileloopin(b)exceptincertainspecialcases(seeReviewQuestion3.19foroneofthem):WhichLooptoUse?36Thethree36Recommendations37Usetheonethatismostintuitiveandcomfortableforyou.Ingeneral,aforloopmaybeusedifthenumberofrepetitionsisknown,as,forexample,whenyouneedtoprintamessage100times.Awhileloopmaybeusedifthenumberofrepetitionsisnotknown,asinthecaseofreadingthenumbersuntiltheinputis0.Ado-whileloopcanbeusedtoreplaceawhileloopiftheloopbodyhastobeexecutedbeforetestingthecontinuationcondition.Recommendations37Usetheonet37NestedLoopsProblem:Writeaprogramthatusesnestedforloopstoprintamultiplicationtable.38MultiplicationTableNestedLoopsProblem:Writea38MinimizingNumericalErrorsNumericerrorsinvolvingfloating-pointnumbersareinevitable.Thissectiondiscusseshowtominimizesucherrorsthroughanexample.Hereisanexamplethatsumsaseriesthatstartswith0.01andendswith1.0.Thenumbersintheserieswillincrementby0.01,asfollows:0.01+0.02+0.03andsoon.

39TestSumMinimizingNumericalErrorsNu39Problem:

FindingtheGreatestCommonDivisor40Problem:Writeaprogramthatpromptstheusertoentertwopositiveintegersandfindstheirgreatestcommondivisor.Solution:Supposeyouentertwointegers4and2,theirgreatestcommondivisoris2.Supposeyouentertwointegers16and24,theirgreatestcommondivisoris8.So,howdoyoufindthegreatestcommondivisor?Letthetwoinputintegersben1andn2.Youknownumber1isacommondivisor,butitmaynotbethegreatestcommonsdivisor.Soyoucancheckwhetherk(fork=2,3,4,andsoon)isacommondivisorforn1andn2,untilkisgreaterthann1orn2.

GreatestCommonDivisorRunProblem:

FindingtheGreatest40Problem:PredicatingtheFutureTuition41Problem:Supposethatthetuitionforauniversityis$10,000thisyearandtuitionincreases7%everyyear.Inhowmanyyearswillthetuitionbedoubled?FutureTuitionRunProblem:PredicatingtheFutu41Problem:PredicatingtheFutureTuition42doubletuition=10000;intyear=1//Year1tuition=tuition*1.07;year++;//Year2tuition=tuition*1.07;year++;//Year3tuition=tuition*1.07;year++;//Year4...FutureTuitionRunProblem:PredicatingtheFutu42Problem:MonteCarloSimulation

43TheMonteCarlosimulationreferstoatechniquethatusesrandomnumbersandprobabilitytosolveproblems.Thismethodhasawiderangeofapplicationsincomputationalmathematics,physics,chemistry,andfinance.ThissectiongivesanexampleofusingtheMontoCarlosimulationforestimating.MonteCarloSimulationRuncircleArea/squareArea=/4.canbeapproximatedas4*numberOfHits/1000000.Problem:MonteCarloSimulati43Usingbreakandcontinue44Examplesforusingthebreakandcontinuekeywords:TestBreak.javaTestContinue.javaTestBreakTestContinueUsingbreakandcontinue44Exam44GuessingNumberProblemRevisited

Hereisaprogramforguessinganumber.Youcanrewriteitusingabreakstatement.45GuessNumberUsingBreakGuessingNumberProblemRevisi45Problem:DisplayingPrimeNumbers46Problem:Writeaprogramthatdisplaysthefirst50primenumbersinfivelines,eachofwhichcontains10numbers.Anintegergreaterthan1isprimeifitsonlypositivedivisoris1oritself.Forexample,2,3,5,and7areprimenumbers,but4,6,8,and9arenot.Solution:Theproblemcanbebrokenintothefollowingtasks:Fornumber=2,3,4,5,6,...,testwhetherthenumberisprime.Determinewhetheragivennumberisprime.Counttheprimenumbers.Printeachprimenumber,andprint10numbersperline.PrimeNumberRunProblem:DisplayingPrimeNumb46(GUI)ControllingaLoopwithaConfirmationDialog47Asentinel-controlledloopcanbeimplementedusingaconfirmationdialog.TheanswersYesorNotocontinueorterminatetheloop.Thetemplateoftheloopmaylookasfollows:intoption=0;while(option==JOptionPane.YES_OPTION){System.out.println("continueloop");option=JOptionPane.showConfirmDialog(null,"Continue?");}SentinelValueUsingConfirmationDialogRun(GUI)ControllingaLoopwith47DebuggingLoopsinIDETools48CompanionWebsiteSupplementsII.C,II.E,andII.G.DebuggingLoopsinIDETools4848Chapter4Loops49Chapter4Loops149MotivationsSupposethatyouneedtoprintastring(e.g.,"WelcometoJava!")ahundredtimes.Itwouldbetedioustohavetowritethefollowingstatementahundredtimes:System.out.println("WelcometoJava!");So,howdoyousolvethisproblem?50MotivationsSupposethatyoune50OpeningProblemProblem:51System.out.println("WelcometoJava!");System.out.println("WelcometoJava!");System.out.println("WelcometoJava!");System.out.println("WelcometoJava!");System.out.println("WelcometoJava!");System.out.println("WelcometoJava!");…

System.out.println("WelcometoJava!");System.out.println("WelcometoJava!");System.out.println("WelcometoJava!");100timesOpeningProblemProblem:3System51IntroducingwhileLoops52intcount=0;while(count<100){System.out.println("WelcometoJava");count++;}IntroducingwhileLoops4intco52Objectives53Towriteprogramsforexecutingstatementsrepeatedlyusingawhileloop(§4.2).TodevelopaprogramforGuessNumberandSubtractionQuizLoop(§4.2.1).Tofollowtheloopdesignstrategytodeveloploops(§4.2.2).TodevelopaprogramforSubtractionQuizLoop(§4.2.3).Tocontrolaloopwithasentinelvalue(§4.2.3).Toobtainlargeinputfromafileusinginputredirectionratherthantypingfromthekeyboard(§4.2.4).Towriteloopsusingdo-whilestatements(§4.3).Towriteloopsusingforstatements(§4.4).Todiscoverthesimilaritiesanddifferencesofthreetypesofloopstatements(§4.5).Towritenestedloops(§4.6).Tolearnthetechniquesforminimizingnumericalerrors(§4.7).Tolearnloopsfromavarietyofexamples(GCD,FutureTuition,MonteCarloSimulation)(§4.8).Toimplementprogramcontrolwithbreakandcontinue(§4.9).(GUI)Tocontrolaloopwithaconfirmationdialog(§4.10).Objectives5Towriteprogramsf53whileLoopFlowChart54while(loop-continuation-condition){//loop-body;Statement(s);}intcount=0;while(count<100){System.out.println("WelcometoJava!");count++;}whileLoopFlowChart6while(l54TracewhileLoop55intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}InitializecountanimationTracewhileLoop7intcount=055TracewhileLoop,cont.56intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}(count<2)istrueanimationTracewhileLoop,cont.8intco56TracewhileLoop,cont.57intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}PrintWelcometoJavaanimationTracewhileLoop,cont.9intco57TracewhileLoop,cont.58intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}Increasecountby1countis1nowanimationTracewhileLoop,cont.10intc58TracewhileLoop,cont.59intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}(count<2)isstilltruesincecountis1animationTracewhileLoop,cont.11intc59TracewhileLoop,cont.60intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}PrintWelcometoJavaanimationTracewhileLoop,cont.12intc60TracewhileLoop,cont.61intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}Increasecountby1countis2nowanimationTracewhileLoop,cont.13intc61TracewhileLoop,cont.62intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}(count<2)isfalsesincecountis2nowanimationTracewhileLoop,cont.14intc62TracewhileLoop63intcount=0;while(count<2){System.out.println("WelcometoJava!");count++;}Theloopexits.Executethenextstatementaftertheloop.animationTracewhileLoop15intcount=63Problem:GuessingNumbers

Writeaprogramthatrandomlygeneratesanintegerbetween0and100,inclusive.Theprogrampromptstheusertoenteranumbercontinuouslyuntilthenumbermatchestherandomlygeneratednumber.Foreachuserinput,theprogramtellstheuserwhethertheinputistoolowortoohigh,sotheusercanchoosethenextinputintelligently.Hereisasamplerun:64GuessNumberOneTimeGuessNumberProblem:GuessingNumbersWrit64Problem:AnAdvancedMathLearningTool

TheMathsubtractionlearningtoolprogramgeneratesjustonequestionforeachrun.Youcanusealooptogeneratequestionsrepeatedly.Thisexamplegivesaprogramthatgeneratesfivequestionsandreportsthenumberofthecorrectanswersafterastudentanswersallfivequestions.65SubtractionQuizLoopProblem:AnAdvancedMathLear65EndingaLoopwithaSentinelValueOftenthenumberoftimesaloopisexecutedisnotpredetermined.Youmayuseaninputvaluetosignifytheendoftheloop.Suchavalueisknownasasentinelvalue.Writeaprogramthatreadsandcalculatesthesumofanunspecifiednumberofintegers.Theinput0signifiestheendoftheinput.66SentinelValueEndingaLoopwithaSentinel66CautionDon’tusefloating-pointvaluesforequalitycheckinginaloopcontrol.Sincefloating-pointvaluesareapproximationsforsomevalues,usingthemcouldresultinimprecisecountervaluesandinaccurateresults.Considerthefollowingcodeforcomputing1+0.9+0.8+...+0.1:doubleitem=1;doublesum=0;while(item!=0){//Noguaranteeitemwillbe0sum+=item;item-=0.1;}System.out.println(sum);Variableitemstartswith1andisreducedby0.1everytimetheloopbodyisexecuted.Theloopshouldterminatewhenitembecomes0.However,thereisnoguaranteethatitemwillbeexactly0,becausethefloating-pointarithmeticisapproximated.ThisloopseemsOKonthesurface,butitisactuallyaninfiniteloop.67CautionDon’tusefloating-poin67do-whileLoop68do{//Loopbody;Statement(s);}while(loop-continuation-condition);do-whileLoop20do{68forLoopsfor(initial-action;loop-continuation-condition;action-after-each-iteration){//loopbody;Statement(s);}69inti;for(i=0;i<100;i++){ System.out.println("WelcometoJava!");}forLoopsfor(initial-action;69TraceforLoop70inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}DeclareianimationTraceforLoop22inti;Declare70TraceforLoop,cont.71inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}Executeinitializeriisnow0animationTraceforLoop,cont.23inti;E71TraceforLoop,cont.72inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}(i<2)istruesinceiis0animationTraceforLoop,cont.24inti;(72TraceforLoop,cont.73inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}PrintWelcometoJavaanimationTraceforLoop,cont.25inti;P73TraceforLoop,cont.74inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}Executeadjustmentstatementinowis1animationTraceforLoop,cont.26inti;E74TraceforLoop,cont.75inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}(i<2)isstilltruesinceiis1animationTraceforLoop,cont.27inti;(75TraceforLoop,cont.76inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}PrintWelcometoJavaanimationTraceforLoop,cont.28inti;P76TraceforLoop,cont.77inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}Executeadjustmentstatementinowis2animationTraceforLoop,cont.29inti;E77TraceforLoop,cont.78inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}(i<2)isfalsesinceiis2animationTraceforLoop,cont.30inti;(78TraceforLoop,cont.79inti;for(i=0;i<2;i++){ System.out.println("WelcometoJava!");}Exittheloop.ExecutethenextstatementaftertheloopanimationTraceforLoop,cont.31inti;E79Note80Theinitial-actioninaforloopcanbealistofzeroormorecomma-separatedexpressions.Theaction-after-each-iterationinaforloopcanbealistofzeroormorecomma-separatedstatements.Therefore,thefollowingtwoforloopsarecorrect.Theyarerarelyusedinpractice,however.for(inti=1;i<100;System.out.println(i++));

for(inti=0,j=0;(i+j<10);i++,j++){//Dosomething}

Note32Theinitial-actionina80Note81Iftheloop-continuation-conditioninaforloopisomitted,itisimplicitlytrue.Thusthestatementgivenbelowin(a),whichisaninfiniteloop,iscorrect.Nevertheless,itisbettertousetheequivalentloopin(b)toavoidconfusion:Note33Iftheloop-continuation81CautionAddingasemicolonattheendoftheforclausebeforetheloopbodyisacommonmistake,asshownbelow:82LogicErrorfor(inti=0;i<10;i++);{System.out.println("iis"+i);}CautionAddingasemicolonatt82Caution,cont.Similarly,thefollowingloopisalsowrong:inti=0;while(i<10);{System.out.println("iis"+i);i++;}Inthecaseofthedoloop,i=0;do{System.out.println("iis"+i);i++;}while(i<10);83LogicErrorCorrectCaution,cont.Similarly,thef83WhichLooptoUse?84Thethreeformsofloopstatements,while,do-while,andfor,areexpressivelyequivalent;thatis,youcanwritealoopinanyofthesethreeforms.Forexample,awhileloopin(a)inthefollowingfigurecanalwaysbeconvertedintothefollowingforloopin(b):Aforloopin(a)inthefollowingfigurecangenerallybeconvertedintothefollowingwhileloopin(b)exceptincertainspecialcases(seeReviewQuestion3.19foroneofthem):WhichLooptoUse?36Thethree84Recommendations85Usetheonethatismostintuitiveandcomfortableforyou.Ingeneral,aforloopmaybeusedifthenumberofrepetitionsisknown,as,forexample,whenyouneedtoprintamessage100times.Awhileloopmaybeusedifthenumberofrepetitionsisnotknown,asinthecaseofreadingthenumbersuntiltheinputis0.Ado-whileloopcanbeusedtoreplaceawhileloopiftheloopbodyhastobeexecutedbeforetestingthecontinuationcondition.Recommendations37Usetheonet85NestedLoopsProblem:Writeaprogramthatusesnestedforloopstoprintamultiplicationtable.86MultiplicationTableNestedLoopsProblem:Writea86MinimizingNumericalErrorsNumericerrorsinvolvingfloating-pointnumbersareinevitable.Thissectiondiscusseshowtominimizesucherrorsthroughanexample.Hereisanexamplethatsumsaseriesthatstartswith0.01andendswith1.0.Thenumbersintheserieswillincrementby0.01,asfollows:0.01+0.02+0.03andsoon.

87TestSumMinimizingNumericalErrorsNu87Problem:

FindingtheGreatestCommonDivisor88Problem:Writeaprogramthatpromptstheusertoentertwopositiveintegersandfindstheirgreatestcommondivisor.Solution:Supposeyouentertwointegers4and2,theirgreatestcommondivisoris2.Supposeyouentertwointegers16and24,theirgreatestcommondivisoris8.So,howdoyoufindthegreatestcommondivisor?Letthetwoinputintegersben1andn2.Youknownumber1isacommondivisor,butitmayno

温馨提示

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

评论

0/150

提交评论