声明:为了大家的共同学习,特推出一些经典书籍的课后练习的答案,答案内容属原创,转载请注明出处,欢迎大家批评指正。 这一序列说明: 1.采用国内的教材:《C++程序设计教程》钱能主编 清华大学出版社 1999 2.在每一章练习解答前会有一个“疑难知识点”概述,这里只代表我自己的观点,也就是我自己现在还不能达到非常熟练,或者我初学时感觉比较模糊的知识。 3. 有一些答案来自网络,里面答案的选题编辑:张朝阳,责任编辑:徐培忠、林庆嘉。在这里表示感谢。以后这里的答案简称“网络版” 4.更多的学习和改进将在《The C++ programming language》答案序列中体现。 序列四:chapter4 一、疑难知识点: 1.三种循环while,do-while,for的一些注意点 (1)文中提到,在这三种循环的判断语句中可以使用逗号语句。其实在C++中好像可以使用语句的地方大多都可以使用逗号语句(但是case里面的常量表达式不能使用逗号语句)。 但需要注意的是:在Java中是没有逗号语句的,在Java中唯一可以使用逗号表达式的是在for循环的第一和第三个语句(第二的判断语句不行哦)。 (2)do-while的do的循环块中可以是没有语句、一条语句或者是多条语句。没有语句和有多条语句时均不能省略{},若只有一跳语句则可以省略{} . 还应该注意while语句的后面要分号; 2.有关switch (1)case里面只能是常量表达式,但不能是逗号表达式(逗号表达式也可以得到常量) (2)switch和case里面只能是int型(当然也包括char、enum、bool) (3)当把case放在最后一个是不能省略冒号;,若不是在最后一句可以省略冒号 (4)注意default语句出现的位置对输出结果的影响 相关例子: #include<iostream> using namespace std; void main() { const int b=6; int c=5; int a; cin>>a; switch(a) { //case (1,2): cout<<"hello2\n";break;//wrong case 5: case 2:cout<<"hello2\n";break; default: cout<<"hello the others\n"; case 3: cout<<"hello3\n";break; case b: cout<<"hellob\n";break; //case c:cout<<"helloc\n";break;wrong,c是变量 case (b/4+6):cout<<"helloc/4\n";break; case b/7:cout<<"helloc/4\n";break; //case 1.5:;wrong case true:;//在最后一句,不能省略冒号; } } 3.注意break和continue的用法,它们一般只用在循环里面,break还可以用在switch里面。注意它们是如何控制循环的运行。 4.有关goto 在C++中,goto好像可以用在任何一个位置(在Java中,goto只能用在一个循环体的前面以控制循环的运行,并且要结合break和continue使用) 一般主张不使用goto,但也有少数名家说适当使用goto有利于程序的编写,初学者还是不用这个好。有关goto可能带来的影响请参考《软件工程》相关课程。 二、课后练习答案:(不抄题目,没有课本的人可以到网上去下一本) 4.01这一道题网络版有完整而且很不错的答案 我的答案:采用do-while编写 #include <iostream> #include<math.h> using namespace std; void main() { double x,temp1=1,temp2=1; int i=1,n=1; cout<<"x="; cin>>x; do { temp2*=n; if(i%2)temp1+=pow(x,n)/temp2; else temp1-=pow(x,n)/temp2; n++; i++; }while(pow(x,n)/(temp2*n)>=1e-8); cout<<"所求的值为:"<<temp1<<endl; } 网络版: (1)do-while #include <iostream.h> #include <math.h> void main() { double sum=1, t=-1, x; int i=1; cout <<"please input a value:\n"; cin >>x; do{ t*=(-1)*x/i; sum+=t; i++; }while(fabs(t)>1e-8); cout <<"sum=" <<sum<<endl; } (2)while #include <iostream.h> #include <math.h> void main() { double sum=1, t=-1, x; cout <<"please input a value:\n"; cin >>x; int i=1; while(fabs(t)>1e-8){ t*=(-1)*x/i; sum+=t; i++; } cout <<"sum=" <<sum<<endl; } (3)for #include <iostream.h> #include <math.h> void main() { double sum=1, t=-1, x; cout <<"please input a value:\n"; cin >>x; for(int i=1; fabs(t)>1e-8; i++){ t*=(-1)*x/i; sum+=t; } cout <<"sum=" <<sum<<endl; }

评论