用C++解决问题第十版 Chapter 4 Procedural Abstraction.docx
- 文档编号:26219239
- 上传时间:2023-06-17
- 格式:DOCX
- 页数:38
- 大小:26.95KB
用C++解决问题第十版 Chapter 4 Procedural Abstraction.docx
《用C++解决问题第十版 Chapter 4 Procedural Abstraction.docx》由会员分享,可在线阅读,更多相关《用C++解决问题第十版 Chapter 4 Procedural Abstraction.docx(38页珍藏版)》请在冰豆网上搜索。
用C++解决问题第十版Chapter4ProceduralAbstraction
Chapter4
ProceduralAbstractionandFunctionsThatReturnaValue
1.SolutionstoandRemarksonSelectedPracticeProgramsandProgrammingProjects
PracticeProgram3:
ValueofStockHoldings
Thisprogramasksforinputofthepriceofastock,thenumberofstocksowned,andoutputsthevalueofthestockholdingindollarsandcents.Theprogramshoulddefineafunctionthatacceptsthepriceofthestockinthreeintvalues:
wholedollars,numeratoroffraction,anddenominatorofthefraction,thenoutputsthevalueofthestockasadouble.Forexample,forastockwhosepricewas77/8dollars,theinputwouldbe77/8andtheoutputwouldbe7.87(usinga"5'sroundodd"rule.)Insupervisedstudentlabs,Ifindtheerrorofhavingafunctionprototypedifferentinsomeessentialwaythanthefunctiondefinitiontobeaprevalenterror.
TheAlgorithminPseudocodeandincode:
//requiredfunction:
//returnvalue=dollars+num/denomwithappropriatecasts
//doubleconvert(intdollars,intnum,intdenom)
//getpricewithfraction,numberofshares
//callfunctiontoconvertpricewithfractiontopriceasdouble
//value=price*(numberofshares)
//outputvalue
//Program:
//problem:
takeinputofnumberofshares,priceasdollars,
//numeratoranddenominatoroffractionalpartofprice,give
//valueofholdings.
doubleconvert(intdollars,intnum,intden);
//acceptasinputthestockpricewithfraction,return
//priceasdouble
#include
usingnamespacestd;
intmain()
{
intdollars,numer,denom,shares;
doubleprice,value;
cout<<"Enterstockpriceandnumberofshares,please.\n"
<<"Enterpriceasintegers:
dollars,numerator,“
<<“denominator."< cin>>dollars>>numer>>denom; cout<<"Enternumberofsharesheld."< cin>>shares; price=convert(dollars,numer,denom); value=price*shares; cout.setf(ios: : fixed); cout.setf(ios: : showpoint); cout.precision (2); cout< < <<"havevalue$"< return0; } doubleconvert(intdollars,intnum,intden) { returndollars+double(num)/den; } Atypicalrunfollows. 14: 24: 24: ~/AW$a.out Enterstockpriceandnumberofshares,please. Enterpriceasintegers: dollars,numerator,denominator. 1058 Enternumberofsharesheld. 100 100sharesofstockwithmarketprice105/8 havevalue$1062.50 14: 24: 32: ~/AW$ PracticeProgram6: CreditCardInterest Thisprogramcomputesinterestonacreditcardbalance.Thetaskisdonewithafunctionthatacceptsinitialbalance,monthlyinterestrate,numberofmonthsforwhichtheinterestmustbepaid.Thevaluereturnedistheinterestdue.Allowrepeatatuser'soption.NBInterestiscompounded.Functionistobeembedinaprogramthatacquiresthesevaluesandoutputstheinterestdue.Repeatofcomputationatusersoptionistobeallowed. Algorithminpseudocode: Functionname: interest input: fetchvaluesfor: doubleinitBalance,doublerate,intmonths. process: declarebalance=initBalance,interest; declareindex=0; while(index { balance=balance*(1+rate); months++; } interest=balance-initBalance; output: interest main: declarebalancerate,interestEarned,months fetchbalance,rate,months interestEarned=interest(balance,rate,months) outputinterestEarned Code: #include usingnamespacestd; //Problem: //giveninitialbalance,rateandmonthsto //run,howmuchinterestaccruesonacreditcard? //allowrepetitionatuser'soption. //computecompoundcreditcardinterest doubleinterest(doubleinitBalance, doublerate,intmonths) { doublebalance=initBalance; inti=0; while(i { balance=balance*(1+rate); i++; } returnbalance-initBalance; } intmain() { doublebalance,rate,interestEarned; intmonths; charans; cout.setf(ios: : showpoint); cout.setf(ios: : fixed); cout.precision (2); do { cout<<"Creditcardinterest"< <<"Enterdoubles: initialbalance,“ <<“monthlyinterestrateas\n" <<"adecimalfraction,e.g.for1.5%“ <<”permonthwrite0.015\n" <<"andintmonthsthebillhasrun.\n" <<"Iwillgiveyoutheinterestthat“ <<”hasaccumulated.\n"; cin>>balance>>rate>>months; interestEarned=interest(balance,rate, months); cout<<"Interestaccumulated=$" < cout<<"Yoryrepeats,anyothercharacter” <<“quits"< cin>>ans; }while('Y'==ans||'y'==ans); return0; } Atypicalrunfollows: 15: 19: 13: ~/AW$a.out Creditcardinterest Enterdoubles: initialbalance,monthlyinterestrateas adecimalfraction,e.g.for1.5%permonthwrite0.015 andintmonthsthebillhasrun. Iwillgiveyoutheinterestthathasaccumulated. 1000 .015 12 Interestaccumulated=$195.62 Yoryrepeats,anyothercharacterquits y Creditcardinterest Enterdoubles: initialbalance,monthlyinterestrateas adecimalfraction,e.g.for1.5%permonthwrite0.015 andintmonthsthebillhasrun. Iwillgiveyoutheinterestthathasaccumulated. 1000 .021 12 Interestaccumulated=$283.24 Yoryrepeats,anyothercharacterquits q 15: 19: 35: ~/AW$ ProgrammingProject2: Clothessizecalculation Themajorproblemforstudentsinthisasinmany‘wordproblems’isdeterminingtheformulasfromtheproblemstatement. Givenheight,weight,age,computeclothessizes: hatSize=weight(lbs.)/height(in.)*2.9 jacketSize(chestsize,in.)= height*weight/288+(1/8)*(age-30)/10 Notecarefullythattheadjustmentonlyoccursforcomplete10yearintervalafterage30,i.e.,ifage<40,thereisnoadjustment! 40<=age<49gets1/8in.adjustment,etc. waist(in.)=weight/5.7+(1/10)*(age-28)/2 NB: adjustmentonlyoccursforcomplete2year intervalafter28 age=29,noadjustment 30<=age<32,1/10inchadjustment. Useafunctionforeachcalculation. Allowrepetitionatuseroption. Nowlet'smakesomedeclarations: intheight;//inches intweight;//lbs intage;//years doublejacketSize;//inchesatchest doublewaist;//inchesatwaist doublehatSize; HatSizeCalculation: hatsize=2.9*double(weight)/height; Thecastisclearer,butisnotstrictlynecessary.Theweightwouldbepromotedautomaticallywhenmultiplicationby2.9occurs.(Thisiswhythe2.9isfirst! ) JacketSizeCalculation: jacket=double(height)*weight/288 if(age>40) jacket=jacket+(age-30)/10*0.125; ThisdependsonthebehavioroftheC/C++languagetoobtaintheresultsrequired.The(age-30/10)arithmeticwillbedoneasint,sincethereisnothingtorequiretypechange.Theintresultwillbethenconvertedtodoubleinthemultiplicationbythe0.125(whichis1/8asadecimal.) WaistSizeCalculation: size=weight/5.7; if(age>=30) size=size+(age-28)/2*0.1; Again,theweightwillbeconvertedtodoubleinthedivisionby5.7.Theexpression,(age-28)/2,willbecomputedasanint,thenbepromotedtodoubleinthemultiplicationby0.1. //problem: Clothessizecalculation: //givenheight(inches)weight(pounds)andage(years) //computejacketsize,waistsize,ininches,andhatsize: //returnshatsizeinstandardhatsizeunits #include usingnamespacestd; doublehatSize(intheight,intweight) { return2.9*double(weight)/height; } //returnsjacketSizeininchesatthechest doublejacketSize(intheight,intweight,intage) { doublejacket=double(height)*weight/288; if(age>40) jacket=jacket+(age-30)/10*0.125; returnjacket; } //returnswaistsizeininches doublewaistSize(intheight,intweight,intage) { doublesize=weight/5.7; if(age>=30) size=size+(age-28)/2*0.1; returnsize; } intmain() { intheight,weight,age; doublehat,jacket,waist; charans; do { cout<<"Givemeyourheightininches,weightin" <<"pounds,andageinyears"< <<"andIwillgiveyouyourhatsize,jacket" <<"size(inchesatchest)"< <<"andyourwaistsizeininches."< cin>>height>>weight>>age; hat=hatSize(height,weight); jacket=jacketSize(height,weight,age); waist=waistSize(height,weight,age); cout.setf(ios: : showpoint); cout.setf(ios: : fixed); cout.precision (2); cout<<"hatsize="< cout<<"jacketsize="< cout<<"waistsize="< cout< <<"enterYorytorepeat,“ <<“anyothercharacterends."< cin>>ans; }while('Y'==ans||'y'==ans); return0; } Atypicalrunfollows: 17: 07: 37: ~/AW$a.out Givemeyourheightininches,weightinpounds,andageinyears andIwillgiveyouyourhatsize,jacketsize(inchesatchest) andyourwaistsizeininches. 6918550 hatsize=7.78 jacketsize=44.57 waistsize=33.56 enterYorytorepeat,anyothercharacterends. y Givemeyourheightininches,weightinpounds,andageinyears andIwillgiveyouyourhatsize,jacketsize(inchesatchest) andyourwaistsizeininches. 6720058 hatsize=8.66 jacketsize=46.78 waistsize=36.59 enterYorytorepeat,anyothercharacterends. n 17: 08: 55: ~/AW$ ProgrammingProject4: NinetyNineBottlesofBeerontheWall //*********************************************************************** // //Thisprogramoutputsthe99bottlesofbeeronthewallsong. //Asimpleloopcallsafunctionthatoutputseachstanza //foraparticularnumberofbottlesofbeer. // //Weuseanotherfunctionthattakesaintegerfrom0-99and //outputsthatint
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 用C+解决问题第十版 Chapter Procedural Abstraction C+ 解决问题 第十