return0;
}
18、编写一个矩形rectangle类,有数据成员长len和宽wid,构造函数retange(int,int).和友元函数
intarea(rectangleT)和intfun(rectangleT)分别计算给定长方形的周长和面积。
#include
usingnamespacestd;
classrectangle
{
public:
rectangle(int,int);
friendintarea(rectangleT);
friendintfun(rectangleT);
private:
intlen,wid;
};
rectangle:
:
rectangle(inta,intb)
{
len=a;
wid=b;
}
intarea(rectangleT)
{
return(T.len*T.wid);
}
intfun(rectangleT)
{
return(2*(T.len+T.wid));
}
intmain()
{
rectangleR(20,30);
cout<<"面积:
"<
cout<<"周长:
"<return0;
}
19、定义一个复数类,用友元函数实现对双目运算符+和*的运算符重载,使其适用于复数运算。
#include
#include
classCComplex
{
#defineerr0.00000001
double_x,_y;
public:
CComplex(doublex=0,doubley=0):
_x(x),_y(y){}
CComplexoperator+(constCComplex&z);
CComplexoperator*(constCComplex&z);
friendostream&operator<<(ostream&os,constCComplex&z);
friendistream&operator>>(istream&is,CComplex&z);
};
intmain()
{
CComplexz1(0,1.2);
CComplexz2(1,1.2);
cout<cout<cin>>z1;
cout<return0;
}
CComplexCComplex:
:
operator+(constCComplex&z)
{
CComplexc;
c._x=_x+z._x;
c._y=_y+z._y;
returnc;
}
CComplexCComplex:
:
operator*(constCComplex&z)
{
CComplexc;
c._x=_x*z._x-_y*z._y;
c._y=_x*z._y+_y*z._x;
returnc;
}
ostream&operator<<(ostream&os,constCComplex&z)
{
if(fabs(z._x)>err)
cout<if(fabs(z._y-1)cout<<(fabs(z._x)>err?
"+i":
"i");
elseif(fabs(z._y+1)cout<<"-i";
elseif(z._y>err)
cout<<(fabs(z._x)>err?
"+":
"")<elseif(z._y<-err)
cout<returnos;
}
istream&operator>>(istream&is,CComplex&z)
{
is>>z._x>>z._y;
returnis;
}
20、输入10个同学的成绩,统计80分以上和不及格的人数,并输出平均值。
#include
usingnamespacestd;
intmain()
{
doublea[10],sum=0,var;
inti,j=0,k=0;
cout<<"请输入10个学生成绩:
"<for(i=0;i<10;i++)
{
cin>>a[i];
sum=sum+a[i];
if(a[i]>=80)
j++;
if(a[i]<60)
k++;
}
var=sum/10;
cout<<"80分以上的人数是:
"<cout<<"不及格的人数是:
"<cout<<"平均分是:
"<return0;
}
21、声明一个类String1,其数据成员为charhead[100],构造函数String(char*Head)实现head的初始化,成员函数voidReverse()实现head内字符串的逆序存放,成员函数voidPrint()实现head内字符串的输出。
#include
#include
usingnamespacestd;
classString
{
public:
String(char*Head);
voidReverse();
voidPrint();
private:
charhead[100];
};
String:
:
String(char*Head)
{
inti=0;
char*p=Head;
while(*p!
='\0')
{
head[i]=*p;
i++;
p++;
}
head[i]='\0';
}
voidString:
:
Reverse()
{
inti=0;
charh[100],*p=head;
while(*p!
='\0')p++;
while(*p!
=head[0])
{
p--;
h[i]=*p;
i++;
}
h[i]='\0';
while(i>=0)
{
head[i]=h[i];
i--;
}
}
voidString:
:
Print()
{
char*p=head;
for(;(*p)!
='\0';p++)cout<<(*p);
cout<}
intmain()
{
char*Head="abcdefgh";
Strings(Head);
cout<<"正序:
";
s.Print();
s.Reverse();
cout<<"逆序:
";
s.Print();
return0;
}
22编写程序形成如下矩阵。
ê2ê1é
4êê3êA=
5ëê
ûú4321ú3211úú2111úú1111ù1111
#include
usingnamespacestd;
intmain()
{
inta[5][5];
intii,jj;
for(ii=0;ii<5;ii++)
{
for(jj=0;jj<5;jj++)
{
if(ii-jj<1)
{
a[ii][jj]=1;
}
else
{
a[ii][jj]=ii+1-jj;
}
}
}
for(ii=0;ii<5;ii++)
{
for(jj=0;jj<5;jj++)
cout<cout<}
return0;
}
23、定义盒子Box类,要求具有以下成员:
可设置盒子形状;可计算盒子体积;可计算盒子的表面积。
#include
usingnamespacestd;
classBox
{
public:
Box(double,double,double);
doublearea();
doublev();
private:
doublex,y,z;
};
Box:
:
Box(doublex1,doubley1,doublez1)
{
x=x