二、课后习题 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; }

评论