c++ primer plus 6th第七章答案

//1

#include    <iostream>
using namespace std;

inline double f(double x,double y){return (2.0*x*y)/(x+y);};


int main()
{
double num,num2;
while(cin>>num>>num2&&num!=0&&num2!=0)
cout<<f(num,num2)<<endl;
return 0;
}

//2

#include    <iostream>
using namespace std;
int enter(double *,int);
void display(double *,int);
double avg(double *,int);


int main()
{
const int SIZE=10;
int count;
double a[SIZE];
(count=enter(a,SIZE))--;
display(a,count);
cout<<"the avg is:"<<avg(a,count)<<endl;
return 0;
}


int enter(double *a,int n)
{
int i;
for(i=0;i<n;i++)
a[i]=0;
i=0;
while(cin>>a[i++]);
return i;
}


void display(double *a,int n)
{
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}


double avg(double *a,int n)
{
double sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum/n;
}


//3

#include    <iostream>
using namespace std;

struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};


void display(const box);
void changeVolume(box&);
void f();


int main()
{
f();
return 0;
}


void f()
{
box a={"asddsa",2.1,3.1,4.1,5.2};
display(a);
changeVolume(a);
display(a);
}


void display(const box a)
{
cout<<"a.maker:"<<a.maker<<endl;
cout<<"a.height:"<<a.height<<endl;
cout<<"a.width:"<<a.width<<endl;
cout<<"a.length:"<<a.length<<endl;
cout<<"a.volume:"<<a.volume<<endl;
}


void changeVolume(box&a)
{
a.volume=(a.length+a.width+a.height)/3;
}

//5

#include    <iostream>


long long f(long long);


int main()
{
using namespace std;
long long n;
cout<<"calculate n!"<<endl;
cin>>n;
cout<<f(n)<<endl;
return 0;
}


long long f(long long n)
{
if(n==0)
return 1;
else
return n*f(n-1);
}

//6

#include    <iostream>


using namespace std;

int Fill_array(double *,int);
void Show_array(double*,int);
void Reverse_array(double*,int);


int main()
{
const int SIZE=10;
double a[SIZE];
int count=0;
count=Fill_array(a,SIZE);
Show_array(a,count);
Reverse_array(a,count);
Show_array(a,count);
return 0;
}


int Fill_array(double *a,int n)
{
int i=0;
while(cin>>a[i++]);
return --i;
}


void Show_array(double*a,int n)
{
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}


void Reverse_array(double*a,int n)
{
double temp;
for(int i=0,j=n-1;i<j;i++,j--)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}


//9

#include    <iostream>
using namespace std;
typedef double (*p[4])(double,double);
double add(double,double);
double sub(double,double);
double mul(double,double);
double div(double,double);
double f(double,double,double (*p[4])(double,double));


int main()
{
double x,y;
x=3,y=9;
p func;
func[0]=add;
func[1]=sub;
func[2]=mul;
func[3]=div;
f(x,y,func);
return 0;
}


double add(double x,double y)
{
return x+y;
}


double sub(double x,double y)
{
return x-y;
}


double mul(double x,double y)
{
return x*y;
}
double div(double x,double y)
{
return x/y;
}


double f(double x,double y,double (*p[4])(double,double))
{
int i;
for(i=0;i<4;i++)
cout<<p[i](x,y)<<endl;
return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章