用C++解决问题第十版Chapter 5 Functions for All Subtasks.docx
- 文档编号:24505569
- 上传时间:2023-05-28
- 格式:DOCX
- 页数:55
- 大小:33.79KB
用C++解决问题第十版Chapter 5 Functions for All Subtasks.docx
《用C++解决问题第十版Chapter 5 Functions for All Subtasks.docx》由会员分享,可在线阅读,更多相关《用C++解决问题第十版Chapter 5 Functions for All Subtasks.docx(55页珍藏版)》请在冰豆网上搜索。
用C++解决问题第十版Chapter5FunctionsforAllSubtasks
Chapter5
FunctionsforAllSubtasks
1.SolutionstoSelectedPracticeProgramsandProgrammingProjects
Detailedsolutionsselectedprojectsarepresentedhere.Therestareessentiallythesameproblems,exceptforwhatisbeingconverted.Notesabouttheremainingproblemsareincluded.
Oneofthemoreimportantthingsinprogrammingisplanning,evenforthesimplestprogram.Iftheplanningisthorough,thecodingwillbeeasy,andtheonlyerrorslikelytobeencounteredaresyntaxerrors,usuallycausedbyeithertypingerrors,aboundaryconditionproblem(frequently,anoffbyoneerror),or(wehopenot)lackofknowledgeofthelanguagedetails.
PracticeProgram1:
Statistics
Computeaverageandstandarddeviationof4entries.
GeneralremarksareinthecodefilewhichIpresenthere:
#include
usingnamespacestd;
/*
Task:
Writeafunctionthatcomputesaverage(Iwillcallthisthearithmeticmeanorsimplythemean)andstandarddeviationoffourscores.Theaverageormean,avg,iscomputedas
avg=(s1+s2+s3+s4)/4
Thestandarddeviationiscomputedas
wherea=avg.Notethatsomestatisticiansmaywishtouse3insteadof4.Wewilluse4.
Input:
scoress1s2s3s4
Output:
standarddeviationandmean.
Required:
Thefunctionistohave6parameters.Thisfunctioncallstwoothersthatcomputethemeanandthestddeviation.Adriverwithaloopshouldbewrittentotestthefunctionattheuser'soption.
*/
//functiondeclaration(orprototype)
//Whenused,themathlibrarymustbelinkedtothe//executable.
#include
usingnamespacestd;
voidaverage(doubles1,doubles2,doubles3,
doubles4,double&avg)
{
avg=(s1+s2+s3+s4)/4;
}
//Preconditions:
averagefunctionmusthavebeencalledon
//thedata,andthevalueoftheaveragepassedintothe//parametera
//Postconditions:
Standarddeviationispassedbackin
//thevariablestdDev
voidsD(doubles1,doubles2,doubles3,doubles4,
doublea,double&stdDev)
{
stdDev=sqrt((s1-a)*(s1-a)+(s2-a)*(s2-a)
+(s3-a)*(s3-a)+(s4-a)*(s4-a))/4;
}
voidstatistics(doubles1,doubles2,doubles3,doubles4,
double&avg,double&stdDev);
//Preconditions:
thisfunctioniscalledwithanysetof
//values.Verylargeorverysmallnumbersaresubjectto
//errorsinthecalculation.Analysisofthissortoferror//isbeyondthescopeofthischapter.
//PostConditions:
avgissettothemeanofs1,s2,s3,s4
//andstdDevissettothestandarddeviationofs1..s4
//functiondefinition:
voidstatistics(doubles1,doubles2,doubles3,doubles4,
double&avg,double&stdDev)
{
average(s1,s2,s3,s4,avg);
sD(s1,s2,s3,s4,avg,stdDev);
}
intmain()
{
doubles1,s2,s3,s4,avg,stdDev;
charans;
do
{
cout<<"Enter4decimalnumbers,"
<<"Iwillgiveyouthemean"
< <<"andstandarddeviationofthedata"< cin>>s1>>s2>>s3>>s4; statistics(s1,s2,s3,s4,avg,stdDev); cout<<"meanof"< <<""< <<"thestandarddeviationof" <<"thesenumbersis"< cout<<"yorYcontinues,anyotherterminates"< cin>>ans; }while('Y'==ans||'y'==ans); return0; } Atypicalrunfollows: 21: 44: 35: ~/AW$a.out Enter4decimalnumbers,Iwillgiveyouthemean andstandarddeviationofthedata 12.313.410.59.0 meanof12.313.410.59is11.3 thestandarddeviationofthesenumbersis0.841873 yorYcontinues,anyotherterminates y Enter4decimalnumbers,Iwillgiveyouthemean andstandarddeviationofthedata 1234 meanof1234is2.5 thestandarddeviationofthesenumbersis0.559017 yorYcontinues,anyotherterminates n 21: 45: 05: ~/AW$ PracticeProgram2: ConvertFeet/InchestoMeters Conversionoffeet/inchestometers: //Task: Convertfeet/inchestometers //Input: alengthinfeetandinches,withpossibledecimal //partofinches //Output: alengthinmeters,with2decimalplaces,which //arethe'centimeters'specifiedintheproblem. //Required: functionsforinput,computation,andoutput. //Includealooptorepeatthecalculationattheuser's //option.Remarks: Thecomputationisasimpleconversionfrom //feet+inchestofeetwithadecimalpart,thentometers. //Outputisrestrictedto2decimalplaces. // //By'metersandcentimeters'theauthormeansthatthe //outputistobemeterswithtwodecimalplaces-whichis //metersandcentimeters.Imentionthisbecausemystudents //alwaysstumbleatthisbecauseofalackofknowledgeof //themetricsystem. #include usingnamespacestd; voidinput(int&feet,double&inches); //Precondition: functioniscalled //Postcondition: //PromptgiventotheuserforinputintheformatFFII, //whereFFisintegernumberoffeetandIIisadouble //numberofinches.feetandinchesarereturnedasentered //bytheuser. voidconvert(intfeet,doubleinches,double&meters); //Preconditions: //REQUIREDCONSTANTS: INCHES_PER_FOOT,METERS_PER_FOOT //inches<12,feetwithinrangeofvaluesforinttype //Postconditions: //metersassigned0.3048*(feet+inches/12) //observethatthecentimeterrequirementismetby //thevalueofthefirsttwodecimalplacesoftheconverted //feet,inchesinput. voidoutput(intfeet,doubleinches,doublemeters); //input: theformalargumentformetersfitsintoadouble //output: //"thevalueoffeet,inches" //"convertedtometers,centimetersis" //wheremetersisdisplayedasanumberwithtwodecimal //places intmain() { intfeet; doubleinches,meters; charans; do { input(feet,inches); convert(feet,inches,meters); output(feet,inches,meters); cout<<"Yorycontinues,anyothercharacterquits" < cin>>ans; }while('Y'==ans||'y'==ans); return0; } voidinput(int&feet,double&inches) { cout<<"Enterfeetasaninteger: "< cin>>feet; cout<<"Enterinchesasadouble: "< cin>>inches; } constdoubleMETERS_PER_FOOT=0.3048; constdoubleINCHES_PER_FOOT=12.0; voidconvert(intfeet,doubleinches,double&meters) { meters=METERS_PER_FOOT*(feet+inches/INCHES_PER_FOOT); } voidoutput(intfeet,doubleinches,doublemeters) { //inches,metersdisplayedasanumberwithtwodecimal //places cout.setf(ios: : showpoint); cout.setf(ios: : fixed); cout.precision (2); cout<<"thevalueoffeet,inches"< < <<"convertedtometers,centimetersis" < } /* Atypicalrunfollows: 06: 59: 16: ~/AW$a.out Enterfeetasaninteger: 5 Enterinchesasadouble: 7 thevalueoffeet,inches5,7.00 convertedtometers,centimetersis1.70 Yorycontinues,anyothercharacterquits y Enterfeetasaninteger: 245 Enterinchesasadouble: 0 thevalueoffeet,inches245,0.00 convertedtometers,centimetersis74.68 Yorycontinues,anyothercharacterquits q 06: 59: 49: ~/AW$ */ PracticeProgram3: ConversionmetrictoEnglish Conversionofmetersbacktofeetandinches //Task: Convertmeterswithcentimeters(justthedecimal //partofmeters)tofeet/inches // //Input: alengthinfeetandinches,withpossibledecimal //partofinches //Output: Alengthmeasuredinfeetwithanydecimalfraction //convertedtoinchesbymultiplyingby12.Fractionsofan //incharerepresentedby2decimalplaces. // //Required: functionsforinput,computation,andoutput. //Includealooptorepeatthecalculationattheuser's //option. // //Remark: Thecomputationisasimpleconversionfrommeters //tofeet,inches,whereincheshasadecimalpart. //Outputisrestrictedto2decimalplaces //Comment: PleaseseeProblem4fordiscussionof'metersand//centimeters' #include usingnamespacestd; voidinput(double&meters); //Precondition: functioniscalled //Postcondition: //Promptgiventotheuserforinputofanumberofmetersas //adouble.inputofadoubleformetershasbeenaccepted voidconvert(int&feet,double&inches,doublemeters); //Preconditions: //REQUIREDCONSTANTS: INCHES_PER_FOOT,METERS_PER_FOOT //Postconditions: //feetisassignedtheintegerpartofmeters(after //conversiontofeetunits)inchesisassignedthe //fractionalpartoffeet(afterconversiontoinchunits voidoutput(intfeet,doubleinches,doublemeters); //input: theformalargumentformetersfitsintoadouble //output: //"thevalueofmeters,centimetersis: " //"convertedtoEnglishmeasureis" // //wheremetersisdisplayedasanumberwithtwodecimal //places intmain() { intfeet; doubleinches,meters; charans; do { input(meters); convert(feet,inches,meters); output(feet,inches,meters); cout<<"Yorycontinues,anyothercharacterquits" < cin>>ans; }while('Y'==ans||'y'==ans); return0; } voidinput(double&meters) { cout<<"Enteranumberofmetersasadouble\n"; cin>>meters; } constdoubleMETERS_PER_FOOT=0.3048; constdoubleINCHES_PER_FOOT=12.0; voidconvert(int&feet,double&inches,doublemeters) { doubledfeet; dfeet=meters/METERS_PER_FOOT; feet=int(dfeet); inches=(dfeet-feet)*INCHES_PER_FOOT; } voidoutput(intfeet,doubleinches,doublemeters) { //metersisdisplayedasadoublewithtwodecimalplaces //feetisdisplayedasint,inchesasdoublewithtwo //decimalplaces cout.setf(ios: : showpoint); cout.setf(ios: : fixed); cout.precision (2); cout<<"Thevalueofmeters,centimeters"< <
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 用C+解决问题第十版Chapter Functions for All Subtasks C+ 解决问题 第十 Chapter
链接地址:https://www.bdocx.com/doc/24505569.html