问答题

【说明】 以下C++程序的功能是计算三角形、矩形和正方形的面积并输出。程序由4个类组成:类 Triangle、Rectangle和Square分别表示三角形、矩形和正方形:抽象类Figure提供了一个纯虚函数getAxea(),作为计算上述3种图形面积的通用接口。 【C++代码】 #include<iostream> #include<cmath> using namespace std; class Figure{ public: virtual double getArea()=0;//纯虚函数 }; class Rectangle : (1) { protected: double height; double width; public: Rectangle(){} Rectangle(double height, double width){ this->height=height; this->width=width; } double getArea(){ return (2) ; } }; class Square: (3) { public: Square(double width){   (4) ; } }; class Triangle: (5) { private: double la,lb,lc; public: Triangle(double la,double lb,double lc){ this->la=la;this->1b=1b;this->lc=lc; } double getArea(){ double s=(la+lb+lc)/2.0; return sqrt(s*(s-la)*(s-lb)*(s-lc)); } int main() { Figure *figures[3]={new Triangle(2,3,3),new Rectangle(5,8), new Square(5)}; for(int i=0;i<3;i++){ cout<<"figures["<<i<<"]area="<<(figures[i])->getArea()<<endl; } return 0; }

【参考答案】

(1) public Figure (2) height *width (3) public Rectangle (4)......

(↓↓↓ 点击下方‘点击查看答案’看完整答案 ↓↓↓)
热门 试题

问答题
【说明】 当一元多项式aixi中有许多系数为零时,可用一个单链表来存储,每个节点存储一个非零项的指数和对应系数。 为了便于进行运算,用带头节点的单链表存储,头节点中存储多项式中的非零项数,且各节点按指数递减顺序存储。例如:多项式8x5-2x2+7的存储结构为: 函数中使用的预定义符号如下: #define EPSI le-6 struct Node( *多项式中的一项* double c; *系数* int e; *指数* struct Node *next; }; typedef struct{ *多项式头节点* int n; *多项式不为零的项数* struct Node *head; }POLY; 【函数】 void Del(POLY *C, struct Node *p) *若p是空指针则删除头节点,否则删除p节点的后继* { struct Node *t; *C是空指针或C没有节点* if(C==NULL||C->head==NULL)return; if( (1) ){ *删除头节点* t=C->head; C->head=t->next; return; } *if* t=p->next; p->next=t->next; }; *Del* void Insert(POLY *C, struct Node *pC) *将pC节点按指数降序插入到多项式C中* *若C中存在pC对应的指数项,则将系数相加;若其结果为零,则删除该节点* { struct Node *t, *tp; *pC为空指针或其系数近似为零* if(pC==NULL || fabs(pC->c) < EPSI)return; if(C->head==NULL){ *若C为空, 作为头节点插入* C->head=pC; pC->next=NULL; C->n++; return; } *if* *若pC的指数比头节点的还大, 插入到头节点之前* if(pC->e>C->head->e){ (2) ; C->head=pC; C->n++; return; } *if* (3) ; t=C->head; while(t!=NULL){ if(t->e>pC->e){ tp=t; t=t->next; } else if(t->e==pC->e){ *C中已经存在该幂次项* t->c+=pC->c; *系数相加* if(fabs(t->c)<EPSI){ *系数之和为零* (4) ; *删除对应节点* C->n--; } (5) ; } else t=NULL; *C中已经不存在该幂次项* } *while* if(t==NULL){ *适当位置插入* pC->next=tp->next; tp->next=pC; C->n++; } *if* }; *Insert*