【2.22】编写一个C++风格的程序,用动态分配空间的方法计算 Fibonacci数列的前20项并存储到动态分配的空间中。
#include<iostream>
using namespace std;
int main()
{
int *p=new int[20];
*p=1;
*(p+1)=1;
cout<<*p<<"\t"<<*(p+1)<<"\t";
p=p+2;
for(int i=3; i<=20; i++){
*p=*(p-1)+*(p-2);
cout<<*p<<"\t";
p++;
if(i%5==0) cout<<endl;
}
return 0;
}
【2.23】编写一个C++风格的程序,建立一个被称为 sroot()的函数,返回其参数的二次方根。重载 sroot()3次,让它返回整数、长整数与双精度数的二次方根(计算二次方根时,可以使用标准库函数sqrt()。
#include<iostream>
#include<cmath>
using namespace std;
double sroot(int x){
return sqrt(x);
}
double sroot(long x){
return sqrt(x);
}
double sroot(double x){
return sqrt(x);
}
int main()
{
int a=1;
long b=1234;
double c=12.34;
cout<<sroot(a)<<endl;
cout<<sroot(b)<<endl;
cout<<sroot(c)<<endl;
return 0;
}
【2.24】编写一个C++风格的程序,解决百钱问题:将一元人民币兑换成1、2、5分的硬币,有多少种换法?
#include<iostream>
using namespace std;
int main()
{
int count=0;
for(int i=0; i<=100/5; i++){
for(int j=0; j<=100/2; j++){
if(100-5*i-2*j>=0){
cout<<i<<"\t"<<j<<"\t"<<100-5*i-2*j<<endl;
count++;
}
}
}
cout<<count<<endl;
return 0;
}
【2.25】编写一个C++风格的程序,输入两个整数,将它们按由小到大的顺序输出。要求使用变量的引用。
#include<iostream>
using namespace std;
void swap(int &a, int &b){
int temp;
temp=a;a=b;b=temp;
}
int main()
{
int a,b;
cin>>a>>b;
if(a>b) swap(a,b);
cout<<a<<" "<<b;
return 0;
}
【2.26】编写C++风格的程序,用二分法求解f(x)=0的根.
#include<iostream>
#include<cmath>
using namespace std;
inline float f(float x){
return 2*x*x*x-4*x*x+3*x-6;
}
int main()
{
float left,right,middle,yleft,yright,ymiddle;
cout<<"input 2 numbers:"<<endl;
cin>>left>>right;
yleft=f(left);
yright=f(right);
do{
middle=(left+right)/2;
ymiddle=f(middle);
if(yright*ymiddle>0){
right=middle;
yright=ymiddle;
}
else{
left=middle;
yleft=ymiddle;
}
}while (fabs(ymiddle)>=1e-6);
cout<<"Root is "<<middle;
return 0;
}