C++-primer-第五版课后习题答案(完整版).docx
Chapter1
Exercise1.1
Reviewthedocumentationforyourcompileranddeterminewhatfilenamingconventionituses.Compileandrunthemainprogramfrompage2.
Windows
Linux
Exercise1.2
Exercise1.2:Changetheprogramtoreturn-1.Areturnvalueof-1isoftentreatedasanindicatorthattheprogramfailed.Recompileandrerunyourprogramtoseehowyoursystemtreatsafailureindicatorfrommain.
Windows
Linux
255?why?pleaselookat?this
Exercise1.3
WriteaprogramtoprintHello,Worldonthestandardoutput.
#includeiostream
intmain()
{
std::coutHello,Worldstd::endl;
return0;
}
Exercise1.4
Ourprogramusedtheadditionoperator,+,toaddtwonumbers.Writeaprogramthatusesthemultiplicationoperator,*,toprinttheproductinstead.
#includeiostream
intmain()
{
std::coutEntertwonumbers:std::endl;
intv1=0,v2=0;
std::cinv1v2;
std::coutTheproductofv1andv2
isv1*v2std::endl;
return0;
}
Exercise1.5
Wewrotetheoutputinonelargestatement.Rewritetheprogramtouseaseparatestatementtoprinteachoperand.
#includeiostream
intmain()
{
std::coutEntertwonumbers:std::endl;
intv1=0,v2=0;
std::cinv1v2;
std::coutTheproductof;
std::coutv1;
std::coutand;
std::coutv2;
std::coutis;
std::coutv1*v2;
std::coutstd::endl;
return0;
}
Exercise1.6
Explainwhetherthefollowingprogramfragmentislegal.
Itsillegal.
[Error]expectedprimary-expressionbeforetoken
Fixedit:removethesparesemicolons.
std::coutThesumofv1
andv2
isv1+v2std::endl;
Exercise1.7
Compileaprogramthathasincorrectlynestedcomments.
Example:
/*
*commentpairs/**/cannotnest.
*cannotnestisconsideredsourcecode,
*asistherestoftheprogram
*/
intmain()
{
return0;
}
Compiledresult(g++):
Exercise1.8
Indicatewhich,ifany,ofthefollowingoutputstatementsarelegal:
std::cout/*;
std::cout*/;
s