《5-8章编程作业》由会员分享,可在线阅读,更多相关《5-8章编程作业(6页珍藏版)》请在金锄头文库上搜索。
1、1. 设计一个立方体类Box,它能提供立方体的体积和表面积。#include iostreamusing namespace std;class Boxfloat a;float volume;float area;public:Box() Box(float r) a=r;void seta(float r) a=r;void getvolume() volume=a*a*a;void getarea() area=6*a*a;void disp()cout 体积: volume ,表面积: area endl;void main()Box obj1(5),obj2;obj2.seta (7
2、);obj1.getarea ();obj1.getvolume ();cout ;obj1.disp ();obj2.getarea ();obj2.getvolume ();cout ;obj2.disp ();system(pause);2编写一个程序,统计学生成绩,其功能包括输入学生的姓名和成绩,按成绩从高到低排列打印输出,对前70%的学生定为合格(PASS),而后30%的学生定义不及格(FAIL)。要求采用面向对象方法编程。#include iostream#include iomanip#include string#define N 10using namespace std;c
3、lass Studentchar name10;int deg;public:void setname(char na) strcpy(name,na);char *getname() return name;void setdeg(int d) deg=d;int getdeg() return deg;class Computeint n;Student naN;public:void getdata() /读入学生的信息int i,tdeg;char tname10;cout n;for (i=0;in;i+)cout 第 i+1 tname tdeg;nai.setname (tnam
4、e);nai.setdeg (tdeg);void sort() /对成绩进行排序int i,j,pick;Student temp;for (i=0;in-1;i+)pick=i;for(j=i+1;j napick.getdeg ()pick=j;temp=nai;nai=napick;napick=temp;void disp()int cutoff,i;cout 输出结果 endl;cout 姓名 成绩 合格否 endl;cout - endl;cutoff=n*7/10-1;for(i=0;in;i+)cout setw(6) nai.getname () setw(3) nai.g
5、etdeg ();if(i=cutoff)cout PASS endl;elsecout FAIL endl;void main()Compute obj;obj.getdata ();obj.sort ();obj.disp ();system(pause);3. 设计一个直线类Line,其中包含3个数据成员,即a、b和c,以及一个求两直线交点的友元函数setpoint和显示数据成员的disp成员函数,并用数据进行测试。两直线的交点为(x,y)的计算公式为:#include #include class Pointdouble x,y;public:Point() ;Point(double
6、 x1,double y1)x=x1;y=y1;void disp()cout ( x , y ) endl;class Lineint a,b,c;public:Line(int a1,int b1,int c1)a=a1;b=b1;c=c1;friend Point setpoint(Line l1, Line l2)double x=(1.0 * l1.b *l2.c -l2.b *l1.c )/(l1.a *l2.b -l2.a *l1.b );double y=(1.0* l1.c *l2.a - l2.c *l1.a )/(l1.a *l2.b -l2.a *l1.b );Poin
7、t p(x,y);return p;void disp()cout a x*x+ b x+ c =0 endl;void main()Point p;Line a(2,3,5), b(-3,4,7);a.disp ();b.disp ();p=setpoint(a,b);p.disp ();4. 编写一个程序,采用成员函数运算符重载方式实现复数的四则运算。并用数据进行测试。#include iostreamusing namespace std;class Complexdouble real,imag;public:Complex() real=imag=0;Complex(double r
8、,double i) real=r;imag=i;Complex operator +(const Complex &c)return Complex(real+c.real ,imag+c.imag );Complex operator -(const Complex &c)return Complex(real-c.real ,imag-c.imag );Complex operator *(const Complex &c)return Complex(real*c.real -imag*c.imag ,real*c.imag +imag*c.real );Complex operato
9、r /(const Complex &c)return Complex(real*c.real +imag*c.imag )/(c.real *c.real +c.imag *c.imag ),(imag*c.real -real*c.imag )/(c.real *c.real +c.imag *c.imag );void disp()if(imag 0)cout real imag i endl;elsecout real + imag i endl;void main()Complex c1(1,2),c2(4,5);Complex c3;c3=c1+c2;cout c1+c2=;c3.disp();c3=c1-c2;cout c1-c2=;c3.disp();c3=c1*c2;cout c1*c2=;c3.disp();c3=c1/c2;cout c1/c2=;c3.disp();system(pause);5. 编写一个程序,采用友元函数运算符重载方式实现复数的四则运算。并用数据进行测试。将上程序相应位置进行修改