第五章 重复

发布时间:   来源:文档文库   
字号:
第五章重複
5-1前言
迴圈指令:whileloopforloopanddo-whileloopPretestloop:whileandforloop(entrance-controlledloopPost-testloop:do-whileloop(exit-controlledloop迴圈內的處理動作至少執行一次
5-2While迴圈
語法:while(條件判斷式
{
statement1statement2}流程圖:
範例程式1
條件判斷式
statement1statement2

計算1+2+…+N,N為輸入值//Sum.cpp#includeusingstd::cin;usingstd::cout;usingstd::endl;intmain({
intN,sum,count;
cout<<"Pleaseinputapositiveinteger:"<cin>>N;count=1;sum=0;while(count<=N{
sum+=count;count++;}
cout<<"Thesumof1+2++"<return0;}
說明:count為計數器,Sum為總和

5-3continuebreak
whilefordo-while三種迴圈都支援continuebreak兩個指令
1.continue程式會忽略其後的敘述,直接跳回到迴圈開頭,
while(condition
{

statement1continue;}
2.break直接跳離迴圈
while(condition
{
statement1break;}statement2

範例程式1Sum2.cpp//Sum2.cpp#includeusingstd::cin;usingstd::cout;usingstd::endl;intmain({
intN,sum,count;
cout<<"Pleaseinputapositiveinteger:"<cin>>N;count=1;sum=0;while(count<=N

{
sum+=count;count++;if(count>Nbreak;}
cout<<"Thesumis"<return0;}
練習1:利用whileloop,計算2+4+6+…+n的總和其中n為偶數練習2:試撰寫一程式,印出3100之間,可被6整除的數值
5-4do-while迴圈
先執行再判斷語法:do{
statement}while(condition
範例程式1
Guess.cpp要求從AE猜一個字母,猜對才算結束程式
#includeusingstd::cin;usingstd::cout;
conditionstatement

usingstd::endl;intmain({
charSecret1=D;charSecret2=d;charguess;do{
cout<<"PleaseinputawordbetweenAtoE\n";cin>>guess;
}while((guess!=Secret1&&(guess!=Secret2;
cout<<"Youhaveagoodluck!Thewordis"<return0;}
本程式可改成while迴圈
練習1:guess.cpp猜不中時,印出"Tryagain",一次就猜中時,印出"Youhavea
goodluck!",第二次猜中時,印出"Youhaveagoodjob!",第三次猜中時,"Youdonthaveagoodluck!",三次以上時,印出"Youhaveapoorluck!"

練習2:寫一程式,自動產生128ASCII符號(hint:使用cout<
5-5for迴圈
1.基本語法
for(起始值設定式;條件判斷式;參數改變式敘述語法範例
for(inti=0;i<10;i++

cout<或寫成inti=0;
for(i=0;i<10;i++cout<
說明:i之起始值為0,每做完一次就自動加一(i++,直至i=9i=10,就自動跳
出迴圈
流程圖:
範例說明1
將原本以while迴圈之程式改為for迴圈//Sumfor.cpp#includeusingstd::cin;usingstd::cout;usingstd::endl;intmain({
intN,sum,count;
cout<<"Pleaseinputapositiveinteger:"<cin>>N;sum=0;
for(initialvalue;condition;parameterchange
statement

for(count=1;count<=N;count++{
sum+=count;}
cout<<"Thesumis"<return0;}範例說明2
Writeaprogramthatusesaforstructuretofindthesmallestofseveralintegers.Assumethatthefirstvaluereadspecifiesthenumberofvaluesremainingandthatthefirstnumberisnotoneoftheintegerstocompare.程式碼
#includeusingstd::cin;usingstd::cout;usingstd::endl;intmain({
cout<<"Pleaseinputtheamountyouwanttocompare:"<
for(inti=2;i<=n;i++
cout<<"Pleaseinputthevalueof1number"<cin>>x;smallest=x;cin>>n;intn;doublex;doublesmallest;


{
cout<<"Pleaseinputthevalueof"<cin>>x;if(x
smallest=x;}
範例說明3
Writeaprogramthatusesaforstructuretosumasequenceofintegers.Assumethatthefirstintegerreadspecifiesthenumberofvaluesremainingtobeentered.Yourprogramshouldreadonlyonevalueperinputstatement.Atypicalinputsequencemightbe5100200300400500wherethe5indicatesthatthesubsequent5valuesaretobesummed.
#includeusingstd::cin;usingstd::cout;usingstd::endl;intmain({
cout<<"Pleaseinputtheamountyouwanttosum:"<
cin>>n;intn;doublex;doublesum=0;}
cout<<"Theminimumvalueof"<return0;

}
範例說明4
WriteaC++programthatusesaforstructuretodetermineandprintthelargestnumberof10numbersinputbytheuser.程式碼
#includeusingstd::cin;usingstd::cout;usingstd::endl;intmain({
doublex;doublemax;
cout<<"Pleaseinputarealnumber"<cin>>x;max=x;
cout<<"Thesumof"<return0;
for(inti=1;i<=n;i++{}
cout<<"Pleaseinputthevalueof"<cin>>x;sum+=x;

for(inti=1;i<10;i++{
cout<<"Pleaseinputarealnumber"<}
cout<<"Themaximumvalueis:"<return0;}
cin>>x;if(x>max
max=x;
2.for迴圈的continuebreak
continue~先執行參數改變式,再跳回起始for迴圈開始處範例說明2CandB.cpp//CandB.cpp#includeusingstd::cin;usingstd::cout;usingstd::endl;intmain(
{
for(inti=2;i<20;cout<<"c",i=i+2
{
cout<<"i";if(i==6continue;cout<<"A";if(i==12break;

cout<<"B";}
cout<return0;}
3.for迴圈的其他寫法
語法說明:(A標準寫法
for(inti=1;i<=N;i++Sum+=i;(B其他寫法
1.
initialvaluemoveinti=1;for(;i<=N;i++sum+=i;
2.
參數改變式移至for迴圈之內inti=1;for(;i<=N;{i++;sum+=i;}
3.
將迴圈內容移至for迴圈的本體內inti=1;
for(;i<=N;sum+=i,i++
練習1:試寫一程式,印出3100之間,可以被6整除的數值練習2:計算1+
1111...之總和122232n2

範例說明3
印出華式與攝氏溫度對照表//Temp.cpp#includeusingstd::cin;usingstd::cout;usingstd::endl;
#includeusingstd::setw;
intmain(
{
doublec;
cout<<"攝氏華氏"<cout<<"______________"<for(inti=1;i<10;i++{
c=10.0*i;
cout<"<<}
cout<<"______________"<return0;}
5-6巢狀迴圈(for之中還有for迴圈
範例說明1
Example:ProgramCode//DisIntM.cpp#includeusingstd::cin;

usingstd::cout;usingstd::endl;#includeusingstd::setw;intmain({
intM=3,N=5;
cout<for(inti=1;i<=M;i++{
for(intj=1;j<=N;j++cout<cout<}return0;}
範例說明2
Writesaprogramthatestimatesthevalueofthemathematicalconstantexbyusingtheformula:
xx2x3
e1...(Pleaseuseaforstructure
1!2!3!
x
程式碼
#includeusingstd::cin;usingstd::cout;usingstd::endl;#includeintmain(

{
doubleexpX=1;doubledelta;doublex;
cout<<"PleaseinputtheexponentialconstantX:";
cin>>x;

for(inti=1;i<=100;i++{
delta=1;
for(intj=1;j<=i;j++
delta*=double(j;
expX+=pow(x,i/delta;
}
cout<<"Theexponentialvaluewithconst"<}
return0;

********************************************************************************
第五章作業
********************************************************************************
1.Theprocessoffindingthelargestnumber(i.e.,themaximumofagroupofnumbersisusedfrequentlyincomputerapplications.Forexample,aprogramthatdeterminesthewinnerofasalescontestwouldinputthenumberofunitssoldbyeachsalesperson.Thesalespersonwhosellsthemostunitswinsthecontest.Writeapseudocodeprogram,thenaC++programthatusesawhilestructuretodetermineandprintthelargestnumberof10numbersinputbytheuser.Yourprogramshouldusethreevariables,asfollows:
counter:Acountertocountto10(i.e.,tokeeptrackofhowmanynumbers
havebeeninputandtodeterminewhenall10numbershavebeenprocessed.
number:Thecurrentnumberinputtotheprogram.largest:Thelargestnumberfoundsofar.
Findthetwolargestvaluesamongthe10numbers.[Note:Youmustinputeachnumberonlyonce.]
2.Writeaprogramthatreadsinthesizeofthesideofasquareandthenprintsahollowsquareofthatsizeoutofasterisksandblanks.Yourprogramshouldworkforsquaresofallsidesizesbetween1and20.Forexample,ifyourprogramreadsasizeof5,itshouldprint****************

3.Apalindromeisanumberoratextphrasethatreadsthesamebackwardsasforwards.Forexample,eachofthefollowingfive-digitintegersisapalindrome:12321,55555,45554and11611.Writeaprogramthatreadsinafive-digitintegeranddetermineswhetheritisapalindrome.(Hint:Usethedivisionandmodulusoperatorstoseparatethenumberintoitsindividualdigits.
4.Inputanintegercontainingonly0sand1s(i.e.,a“binary”integerandprintitsdecimalequivalent.Usethemodulusanddivisionoperatorstopickoffthe“binary”number’sdigitsoneatatimefromrighttoleft.Muchlikeinthedecimalnumbersystem,wheretherightmostdigithasapositionalvalueof1,thenextdigitlefthasapositionalvalueof10,then100,then1000,andsoon,inthebinarynumbersystem,therightmostdigithasapositionalvalueof1,thenextdigitlefthasapositionalvalueof2,then4,then8,andsoon.Thusthedecimalnumber234canbeinterpretedas4*1+3*10+2*100.Thedecimalequivalentofbinary1101is1*1+0*2+1*4+1*8or1+0+4+8,or13.
5.Writeaprogramthatreadsthreenonzerointegersanddeterminesandprintswhethertheycouldbethesidesofarighttriangle.
6.Acompanywantstotransmitdataoverthetelephone,butisconcernedthatitsphonescouldbetapped.Allofthedataaretransmittedasfour-digitintegers.Thecompanyhasaskedyoutowriteaprogramthatencryptsthedatasothatitcanbetransmittedmoresecurely.Yourprogramshouldreadafour-digitintegerandencryptitasfollows:Replaceeachdigitby(thesumofthatdigitplus7modulus10.Then,swapthefirstdigitwiththethird,swaptheseconddigitwiththefourthandprinttheencryptedinteger.Writeaseparateprogramthatinputsanencryptedfour-digitintegeranddecryptsittoformtheoriginalnumber.
7.Writeaprogramthatusesaforstructuretosumasequenceofintegers.Assumethatthefirstintegerreadspecifiesthenumberofvaluesremainingtobeentered.Yourprogramshouldreadonlyonevalueperinputstatement.Atypicalinput

sequencemightbe5100200300400500
wherethe5indicatesthatthesubsequent5valuesaretobesummed.
8.Writeaprogramthatusesaforstructuretofindthesmallestofseveralintegers.Assumethatthefirstvaluereadspecifiesthenumberofvaluesremainingandthatthefirstnumberisnotoneoftheintegerstocompare.
9.Oneinterestingapplicationofcomputersisthedrawingofgraphsandbarcharts(sometimescalled“histograms”.Writeaprogramthatreadsfivenumbers(eachbetween1and30.Foreachnumberread,yourprogramshouldprintalinecontainingthatnumberofadjacentasterisks.Forexample,ifyourprogramreadsthenumberseven,itshouldprint*******.
10.Writeaprogramthatprintsatableofthebinary,octalandhexadecimalequivalentsofthedecimalnumbersintherange1through256.Theanswerlookslikeas
DecimalBinary12...245246247248249250251252253

011110101365011110110366011110111367011111000370011111001371011111010372011111011373011111100374011111101375
f5f6f7f8f9fafbfcfd

OctalHexadecimal
12
00000000110000000102

254255256

011111110376011111111377100000000400
feff100
11.WriteaC++programthatusesawhilestructureandthetabescapesequence\tto
printthefollowingtableofvalues:N10*N12345
12.nfactorialisdefinedasfollows:n!nn1n2...1
(AWriteaprogramthatreadsanonnegativeintegerandcomputesandprintsits
factorial.
(BWritesaprogramthatestimatesthevalueofthemathematicalconstanteby
usingtheformula:e1
111
...1!2!3!
100*N100200300400500
1000*N10002000300040005000
1020304050
(CWritesaprogramthatestimatesthevalueofthemathematicalconstantex
byusingtheformula:
xx2x3
e1...
1!2!3!
x

13.Writeaprogramthatuseaforstructuretocalculateandprinttheaverageof
severalintegers.Assumethelastvaluereadisthesentinel9999.Atypicalinputsequencemightbe
10811799999
14.Driversareconcernedwiththemileageobtainedbytheirautomobiles.Onedriver

haskepttrackofseveraltankfulsofgasolinebyrecordingmilesdrivenandgallonsusedforeachtankful.DevelopaC++programthatusesawhilestructuretoinputthemilesdrivenandgallonsusedforeachtankful.Theprogramshouldcalculateanddisplaythemilespergallonobtainedforeachtankful.Afterprocessingallinputinformation,theprogramshouldcalculateandprintthecombinedmilespergallonobtainedforalltankfuls.
Enterthegallonsused(-1toend:12.8Enterthemilesdriven:287
Themiles/gallonforthistankwas22.421875Enterthegallonsused(-1toend:10.3Enterthemilesdriven:200
Themiles/gallonforthistankwas19.417475Enterthegallonsused(-1toend:5Enterthemilesdriven:120
Themiles/gallonforthistankwas24.000000Enterthegallonsused(-1toend:-1
Theoverallaveragemiles/gallonwas21.601423
15.DevelopaC++programthatwilldeterminewhetheradepartment-storecustomer
hasexceededthecreditlimitonachargeaccount.Foreachcustomer,thefollowingfactsareavailable:aAccountnumber(anintegerbBalanceatthebeginningofthemonth
cTotalofallitemschargedbythiscustomerthismonth
dTotalofallcreditsappliedtothiscustomer'saccountthismontheAllowedcreditlimit
Theprogramshoulduseawhilestructuretoinputeachofthesefacts,calculatethenewbalance(=beginningbalance+chargescreditsanddeterminewhetherthenewbalanceexceedsthecustomer’screditlimit.Forthosecustomerswhosecreditlimitisexceeded,theprogramshoulddisplaythecustomer'saccountnumber,creditlimit,newbalanceandthemessage“Creditlimitexceeded”.

Enteraccountnumber(-1toend:100Enterbeginningbalance:5394.78Entertotalcharges:1000.00Entertotalcredits:500.00Entercreditlimit:5500.00Account:100Creditlimit:5500.00Balance:5894.78CreditLimitExceeded.
Enteraccountnumber(-1toend:200Enterbeginningbalance:1000.00Entertotalcharges:123.45Entertotalcredits:321.00Entercreditlimit:1500.00
Enteraccountnumber(-1toend:300Enterbeginningbalance:500.00Entertotalcharges:274.73Entertotalcredits:100.00Entercreditlimit:800.00
Enteraccountnumber(-1toend:-1
16.Onelargechemicalcompanypaysitssalespeopleonacommissionbasis.Thesalespeoplereceive$200perweekplus9percentoftheirgrosssalesforthatweek.Forexample,asalespersonwhosells$5000worthofchemicalsinaweekreceives$200plus9percentof$5000,oratotalof$650.DevelopaC++programthatusesawhilestructuretoinputeachsalesperson’sgrosssalesforlastweekandcalculateanddisplaythatsalesperson’searnings.Processonesalesperson’sfiguresatatime.Entersalesindollars(-1toend:5000.00Salaryis:$650.00
Entersalesindollars(-1toend:6000.00Salaryis:$740.00
Entersalesindollars(-1toend:7000.00

Salaryis:$830.00
Entersalesindollars(-1toend:-1
17.DevelopaC++programthatusesawhilestructuretodeterminethegrosspayforeachofseveralemployees.Thecompanypays“straight-time”forthefirst40hoursworkedbyeachemployeeandpays“time-and-a-half”forallhoursworkedinexcessof40hours.Youaregivenalistoftheemployeesofthecompany,thenumberofhourseachemployeeworkedlastweekandthehourlyrateofeachemployee.Yourprogramshouldinputthisinformationforeachemployeeandshoulddetermineanddisplaytheemployee’sgrosspay.Enterhoursworked(-1toend:39
Enterhourlyrateoftheworker($00.00:10.00Salaryis$390.00
Enterhoursworked(-1toend:40
Enterhourlyrateoftheworker($00.00:10.00Salaryis$400.00
Enterhoursworked(-1toend:41
Enterhourlyrateoftheworker($00.00:10.00Salaryis$415.00
Enterhoursworked(-1toend:-1
18.Theprocessoffindingthelargestnumber(i.e.,themaximumofagroupofnumbersisusedfrequentlyincomputerapplications.Forexample,aprogramthatdeterminesthewinnerofasalescontestwouldinputthenumberofunitssoldbyeachsalesperson.Thesalespersonwhosellsthemostunitswinsthecontest.Writeapseudocodeprogram,thenaC++programthatusesawhilestructuretodetermineandprintthelargestnumberof10numbersinputbytheuser.Yourprogramshouldusethreevariables,asfollows:
counter:Acountertocountto10(i.e.,tokeeptrackofhowmanynumbers
havebeeninputandtodeterminewhenall10numbershavebeenprocessed.

number:Thecurrentnumberinputtotheprogram.largest:Thelargestnumberfoundsofar.
19.Writeaprogramthatprintsthefollowingdiamondshape.Youmayuseoutput
statementsthatprinteitherasingleasterisk(*orasingleblank.Maximizeyouruseofrepetition(withnestedforstructuresandminimizethenumberofoutputstatements.
*****************************************

本文来源:https://www.2haoxitong.net/k/doc/9af0cf4d0912a21615792902.html

《第五章 重复.doc》
将本文的Word文档下载到电脑,方便收藏和打印
推荐度:
点击下载文档

文档为doc格式