




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
C++程序设计基础课后习题
Homeworkproblems
Whataretheelementsofa1-1object-orientedsystem?
Answer:theobject-orientedsystemcontainsthreeelements:
objects,classes,andinheritance.
1-2pleasedetermineifthefollowingstatementsarevalidand
why:
Answer:1)/*Thisis/*aexplanation*/sentence.The
compilerthinkstheannotationstatementisfinishedwhenit
encountersthefirst*/.Theactualannotationisthoughtto
be/*Thisis/*aexplanation*/sentence.*//Thisis
aexplanationsentence.//
Legal./Thisisanexplanationsentence./Thisisa
explanationsentence.Commentsymbol/**/and//nomatch.
//Thisisaexplanationsentence.Unmatchedannotation
symbols*/mightcausecommentstoenderrorsprematurely,
similarto(1).
Whatarethelegalc++variablenamesineachofthefollowing
lexicalsymbols?Italsoexplainswhyotherlexicalsymbolsare
illegal.
Answer:invalidvariablename:3ndcannotbeginwithanumber.
Youcanonlystartwith26lettersorunderscores.The@price
isnotlegalatthebeginning.A*b*isanillegalvariable
namecharacter.PIillegalvariablenamecharacter.Depthis
notlegalatthebeginning.Thevia.numdot"isaninvalid
variablenamecharacter.
1-4pointsouttheerrorsinthefollowingprogram:
Answer:#include<iostream.h>
Voidmain()
Const:x=1;//constshouldnothaveacolon.
Y=6;//yisassignedwithoutdefinition.
X=x+y;//xisconstconstantandcannotbereassigned.
Cout<<'X='<<<<<<<<//stringsshouldbewritten
indoublequotationmarks,"X=".
1-5trytoanalyzethevaluesofthefollowingfourexpressions
todetermineiftheirvaluesarethesame.Andcomparethe
calculationrulesofexpressionsinac++andwhatarethe
similaritiesanddifferencesinmathematicsoperationrules,
soastoexplainthefourexpressionevaluationprocessandthe
calculationofthevariousstepsoftheintermediateresults.
1)2000*5/72)2000/7*53)5/7*7*2)5/7*5)5/7*5)
5/7*5)5/7*1000
Answer:1)2000*5/7=10000/7=14282)2000/7*5=285*
5=14253)5/7*2000=0*2000=0*2000=0*2000=0.714286
*2000=1428.575)1000*5/7=7146)5/7*1000=0
1-6unlessforcedtypeconversionisperformed,thefour
arithmeticresultsbetweenintegersarestillintegers.The
integeranddecimalarithmeticresultsinthehigherprecision
principle.3.2.6pleasepointoutthedifferencesofthefour
variablesvarl〜var4shownbelow:
Answer:1)intvarl=1999;Variistheintegervariable.2)
constvar2=1999;Var2istheintegerconstant.3)volatile
intvar3=1999;Integervar3isthememoryvariable,andthe
programwillnotbestoredintheregister.3)constvolatile
var4=1999;Integervar4ismemoryconstant.
TherearefourmembersofA:A,B,CandDinAdormitory.They
meetthefollowingconditions:1)Aneversingsinthedormitory;
2)onlyAisinthedormitory,BandDsing.3)Cdoesn'tsing
inanysituation.Accordingtotheconditionsgiven,writethe
c++logicalexpressionfor"nobodysinginginthedorm”.
A:Aisinthedormitory,B,DmeansBandDsing.Aslongas
BandDarenotsinginginthedormitory,nooneissingingin
thedormitory,nomatterwhatAorCis.AslongasAisnot
inthedorm,BandDdon'tsing,andnooneinthedormcansing.
Sothefullconditionalexpressioncanbewrittenas:solution
one:!A).(necessaryandsufficientcondition)solutiontwo:!
(B&D);Method:three!B&&!D;(actually,thelogical
transformationofsolutiontwo).A;
Whichstatementshavethesamefunctioninthefollowingfour
ifstatements?1)if(pl)if(p2)statement;2)if(p2)if(pl)
statement;3)thestatement;4)if(pl,|,|p2)statement;
Answer:1),2),3)thesamefunction,bothconditionalpland
p2,whenthestatementisexecuted.
1-9afactoryhasprioritymaintenanceonthefollowing
equipment:productioncapacityisgreaterthan1000unitsper
hour,andhasbeenrepairedlessthan5timesinthepast,or
morethan10yearsofservicelife.Pleasecompileanddebug
thec++programthatdeterminesiftheplant'sequipment
shouldbemaintainedfirst.
Answer:thekeytotheproblemistowritethelogical
expressionofprioritymaintenance:ability>1000&&ers.1:
#include<iostream.H>
Voidmain()
Intability,repair,lifetime;
Cout<<"pleaseentertheproductioncapacityofthedevice
(piece/hour),pastmaintenancetimesandservicelife
(year):";
Cin>,>,>repair>lifetime.
"If”(ability>1000&&)
Theequipmentshouldberepairedfirst.;
Theelse
Cout<<"thedeviceshouldnotberepairedfirst.
)
Method2:
If(ability>1000){
If(repair<5||lifetime>10)
Theequipmentshouldberepairedfirst.;
)
Theelse
Cout<<"thedeviceshouldnotberepairedfirst.
Usethesecondmethodshouldpayattentiontoistheif-else
statementsmatchingambiguity:c++,theelseconnectedtothe
firstandisvisibleifnotmatching,theontologyasthesecond
iftheelsearenotvisible,sotheelseifmatchedwithablity
infront.Butforthereadabilityofaprogram,thesecond
programmingapproachisnotadvocated,andthefirstisbetter
forreadability.
1-10trytocreateac++programthatsimulatesacalculator
forfouroperations.
Answer://sourcecodeisasfollows:
#include<iostream.H>
Voidmain()
DoubleDNumADNumB;
CharCComput;
TheInputnumberandoperator
“('p'toquit,'c,toclean)
Cin>>DNumA;
BoolBComputer=true;
While(BComputer)
CComput=,p,;
Cin>>CComput;
Theswitch(CComput){
Case'+':
Cin>>DNumB;
DNumA=DNumA+DNumB;
Cout<<\t=,z<<<<<<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<<<<<<<<
Break;
Case:'*'
Cin>>DNumB;
DNumA=DNumA*DNumB;
Cout<<\t=,z<<<<<<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<<<<<<<<
Break;
Case'-':
Cin>>DNumB;
DNumA=DNumA-DNumB;
Cout<<\t="<<<<<<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<<<<<<<<
Break;
Case'/':
Cin>>DNumB;
If(DNumB!=0.0)
(
DNumA=DNumA/DNumB;
Cout<<\t=,z<<<<<<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<<<<<<<<
}
Theelse
Zerodivisor.
Break;
Case'c
TheInputnumberandoperator
“('p'toquit,'c'toclean):“
Cin>>DNumA;
Break;
Default:
BComputer=false;
TheProgramquited.
Break;
)
}
)
//programcompute.CPPrunstheresults:
Inputnumberandoperator('p'toquit,'c'toclean)
6.7*5
=33.5
89.87
=56.37
c
Inputnumberandoperator('p,toquit,'c'toclean):
5.4/7.908=0.682853
1to11.Writeascheduletoprintprogram,accordingtothe
inputoftheweek(1~5)toprintoutthedayofthecourse,
andtheprintingprocesscanbeloop,andsettheendofthe
cycle.
A:thec++languageprovidesthreetypesofloopstructures:
whilestatements,do_whi1estatements,andforstatements.
Thisproblemcanbedoneusingeitherawhileordo_whileloop
controlmethod.Thewhilestatementfirstdeterminesthe
evaluationoftheexpression,
Iftheexpressionresultistruethentheloopbodyisexecuted,
otherwisethewhilestatementisended;Do_whilestatementis
moresuitablefortheloopbodyexecutedatleastonce,its
characteristicistoexecutetheloopbodyfirst,andthenjudge
expressionisevaluatedasaresult,iftheexpressionresults
istruecontinuestoimplementtheloopbody,otherwiseend
do_whilestatements,executingthenextstatement.
Methodone:
//sourcecodeisasfollows:
#include"iostream,h”
Voidmain()
(
Intday=1;
While(day!=0){
"Cout"<<"\nPleaseinputthedayyouwanttobesure
(1~5=daynumber;0=end):\t.
Cin>>day.
Theswitch(day){
Case1:cout<<"Monday:…“<<endl;Break;
Tuesday:"Tuesday".<<endl;Break;
Case3:cout<<"Wednesday,.."<<endl;Break;
Case4:cout<<Thursday:<<endl;Break;
Case5:cout<<"Friday:"<<endl;Break;
Case0:cout.Break;
Default:cout,pleasereinput.
)
Method2:
#include“iostream,h”
Voidmain()
(
Intday;
Do{
"Cout"<<nPleaseinputthedayyouwanttobesure”
(1~5=daynumber;0=end):\t.
Cin>>day.
Theswitch(day){
Case1:cout<<"Monday:…“<<endl;Break;
Tuesday:"Tuesday".<<endl;Break;
Case3:cout<<"Wednesday,.."<<endl;Break;
Case4:cout<<Thursday//<<endl;Break;
Case5:cout<<"Friday:"<<endl;Break;
Case0:cout.Break;
Default:cout<<<<"<<”>
)
}while(day!=0)
}
//programpromptsfor1~5numberqueryMondaytoFriday,
0endquery,inputotherfigureswereup//inputerrorsand
re-enteryourrequirementsnumberquery.
1-12peopleuselettersinsteadofdecimalnumbercalculation,
writethefollowingformula:EGALxL-LAGEpleaseusec++
programming,findouttheselettersinsteadofNumbers.
Answer://sourcecodeisasfollows:
#include<iostream.H>
Voidmain()
Inte,g,a,1,tempal,tempa2,tempb,see;
For(e=0;e<=9;e++){
For(g=0;g<=9;g++){
For(a=0;a<=9;a++){.
For(1=0;1<=9;1++){.
Tempal=(e*1000+g*100+a*10+1);
Tempa2=tempal*1;
Tempb=1*1000+a*100+g*10+e;
See=(e-g)*(e-a)*(g-a)*(g-1)*(a-l).
If(tempa2===tempb&&see!=0)
Thecout<<<<<<<<<<<<<><<<<<<<><<<<
<><<<><<<<<><<<<<><<<<<<<>><<<<
<<><<<<
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
<<<<<<<<<<<<<><<<<<<<<<<<<<<<><
<<<<<<<<<<<<<<<<
)
//theresultoftheprogramis1089*9---9801
1-13trytowriteaprogramthatenterstwopositiveintegers
andasksfortheirgreatestcommonandleastcommonmultiples.
Answer:aandbareintegergreatestcommondivisorandleast
commonmultipleproblemsthekeyistofindthegreatestcommon
divisortfirst,mathematicianEuclid(Euclid)hasgivena
classicalsolution:step1:ifa<b,theexchangeofaandb.
Steptwo:letrbetheremainderofa/b.Step3:ifr=0,then
t=bandterminate.Otherwise,a=b,b=r,andturntostep
two.Soifwefigureoutthelargestcommondivisort,wecan
figureouttheleastcommonmultipleofatimesbovert.//
sourcecodeisasfollows:
#include<iostream.H>
Int,int,
Voidmain()
TheInput2Numbers:
Inta,b,t;
Cin>a>.
T=gray(a,b);
Maxcommondivisor.
<<<<<<<<<<<<<<<<<<<><<<<<<<<<<<
<<<<<<>>>
}
Intm,intn//tossandturntomaximizethecommondivisor.
(
Intml,r;
If(m<n){ml=m;M=n;N=ml;}
R=m%n;
While(r!=0){m=n;N=r;R=m%n;}
Return(n);
//programrunresults:
Input2Numbers:
23445
Maxcommondivisor:9
Mincommonmultiple:1170
Pressanykeytocontinue
1-14ABCDEFGHeightpeoplestandinarow,thenumbershown
infigure1.10startsat1.Whofirstreportedto19431005?
Answer:#include<stdio.H>
Voidmain()
(
Longanum=19431005;
Constlongnum=8;
Theswitch(numanum%)
Case0:printf("H\n");Break;
Case1:printf("A\n");Break;
Case2:printf("B\n");Break;
Case3:printf("C\n");Break;
Case4:printf("D'n");Break;
Case5:printf("E\n");Break;
Case6:printf("F\n");Break;
Case7:printf("G\n");Break;
Default:printf("wrong!\n");Break;
1-15ofancientChinesemathematicsmagnumopus"ninechapter
arithmetic“volume138entitled〃atotaloffiveWells,the
hometwoBing(pumpingwithcoldwater),suchas(in)aBing
b;bthreeBingisinsufficient,suchasacBing;fourBing
cisinsufficient,suchasreadingaBing;butylfiveBingis
insufficient,suchashepatitisaBing;esixBingis
insufficient,suchasarmorBing,and.
Askthewell,thedirector'sgeometry.Answer:sevenzhangs2
feetoneinchholedepth,aBingtwozhangssixfeetfiveinches
long,bBingtenninefeetoneinchlong,cBingshakuhachia
post,thefourincheslong,butylBingtenthreefeet9inches
long,eBingsevenfeet,sixincheslong.""
Answer:a,b,c,d),fivestringx,y,z,s,t,welldepth,u,
thenlisttheequations:(2x+y=u|3y+z=u+s={4
zu|5s+t=u(t+6x=usolutionequationstox,y,z,
s,t,respectively,equalto265/721mmmm,191/721,191/721,
191/721,76/721m,andwelldeeply1m.
1-16,howmanywaysaretheretochangeadollartoanickel
for5,2,and1
Answer:541kinds#include<iomanip>
#include<iostream>
UsingnamespaceSTD.
Themain(){
Intn=0;
For(int1=0;I<=20;I++)
For(intj=0;j<=50;j++){
Intisequalto100minusItimes5minusjtimes2.
Ifk,>=0.
Cout<<setw++n(4)<<<<":1<<"setw(3)<<<<k
",2"<<setw(3)<<<<j",5"<<setw(3)<<I<<"zhang
"<<endl;
If(!(n%200))getchar();
)
}
Onein17scientistshadamathproblem:therewereacow.It
hasasmallcowatthebeginningofeveryyear;Everysmal1cow
willhaveasmallcowatthebeginningofeveryyearsincethe
fourthyear.Inthislaw,ifnocattledie,howmanycowsare
thereinthe20thy
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 头晕头痛的护理
- 2025年学校教学学年工作方案
- 2025年电化教学工作方案
- 流产后卫生护理
- 2025年老师工作方案模板
- 村两委2025年度工作方案例文
- 发热的诊断思路
- 科技教育特色学校汇报
- 省森林资源管理汇报
- 道闸知识培训课件
- 中小学学校落实中央八项规定自查报告
- 2025年山东鲁泰控股集团有限公司下属驻陕西煤矿企业招聘(150人)笔试参考题库附带答案详解
- 2025届上海市浦东新区高三二模英语试卷(含答案)
- 2025-2030羊毛制品行业市场调研分析及发展趋势与投资前景研究报告
- 房建资料员知识培训课件
- 新零售背景下的电子商务尝试试题及答案
- 2024-2025学年高一政治统编版下学期期中考试测试卷B卷(含解析)
- 《商务沟通与谈判》课件 第二章 商务沟通原理
- 内蒙古自治区呼和浩特市2025届高三第一次模拟考试物理答案
- 开曼群岛公司法2024版中文译本(含2024年修订主要内容)
- TSGD7002-2023-压力管道元件型式试验规则
评论
0/150
提交评论