正文

钱能的《C++程序设计教程》序列五:chapter5第二部分2005-08-03 15:02:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/xiangyu/3414.html

分享到:

二、课后习题 5.4这道题出得很不错,考察了很多知识点,只要有一点细节你没有注意就可能出现错误。 主要注意点: (1)数值调用是不改变值 (2)全局变量在任何一个函数内都会改变它的值 (3)静态变量只初始化一次(在函数调用时只在第一次赋值) 答案: Main--x=5,y=1,n=1 Func--x=6,y=21,n=11 Main--x=5,y=1,n=11 Func--x=8,y=31,n=21 5.5 #include<iostream> using namespace std; int fib(int n);//函数声明 void main() {     int n;     cout<<"Input an integer:";     cin>>n;     cout<<"第n项的值是:"<<fib(n)<<endl; } int fib(int n) {     int i,a=1,b=1,c=1;     for(i=3;i<=n;i++)     {         c=a+b;         a=b;         b=c;     }     return c; } 5.6 #include<iostream> using namespace std; double p(int n, double x)//函数声明和定义一起 {   if(n==0)     return 1;   if(n==1)     return x;   return ((2*n-1)*x*p(n-1,x)-(n-1)*p(n-2,x))/n; } void main() {     int n;     double x;     cout<<"Please input one integer and one double:";     cin>>n>>x;     cout<<"所求的值为:"<<p(n,x)<<endl; } 5.7大家如果注意的话就会发现,在所有迭代法的题目中使用的都是do——while格式,这是一般的习惯。 #include<iostream> #include<math.h> using namespace std; void main() {     double x1=3.14159/4, xn=3.14159/4;     do     {         x1=xn;         xn=x1+(cos(x1)-x1)/(sin(x1)+1);     }     while(fabs(xn-x1)>=1e-6);     cout<<"所求的值为:"<<xn<<endl; } 5.8再次强调:不能用返回参数来区别重载。 这题主要涉及函数类型的隐式转换。 #include <iostream> using namespace std; void display(double a){ cout <<"A double: " <<a <<endl; } void display(int a){ cout <<"A int: " <<a <<endl; } void display(char a){ cout <<"A char: " <<a <<endl; } void main() {   double a=100.0;   float f=1.0;   int n=120;   char ch='b';   short s=50;   display(a);   display(f);   display(n);   display(ch);   display(s); } 5.9 主要找出递归关系式: f(n)=f(n-3)+f(n-1) n>=4     =1 n=1,2,3 答案: #include<iostream> using namespace std; int f(int); void main() {     int fnum=1,snum=1,tnum=1,sum=1,n;     cout<<"第";     cin>>n;     cout<<"年";     cout<<"母牛的数目是:"<<f(n)<<endl; } int f(int n) {     if(n>=4) return f(n-3)+f(n-1);     return 1; }

阅读(3591) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册