C++計(jì)算圓形、矩形和三角形的面積
題目描述
運(yùn)用多態(tài)編寫程序,聲明抽象基類Shape,由它派生出3個(gè)派生類: Circle(圓形)、Rectangle(矩形)、Triangle(三角形),用一個(gè)函數(shù)printArea()分別輸出以上三者的面積(結(jié)果保留兩位小數(shù)),3個(gè)圖形的數(shù)據(jù)在定義對(duì)象時(shí)給定。
輸入
圓的半徑 矩形的邊長 三角形的底與高
輸出
圓的面積
矩形的面積
三角形的面積
注意:每一行后有回車符
樣例輸入
12.6 4.5 8.4 4.5 8.4
樣例輸出
area of circle=498.76
area of rectangle=37.80
area of triangle=18.90
代碼實(shí)現(xiàn)
#include<iostream>
#include<iomanip>
#define PI 3.1415926
using namespace std;
class Shape {
public:
virtual double printArea()=0;
};
class Circle:public Shape {
private:
double r;
public:
Circle(double x) {
r=x;
}
virtual double printArea() {
return PI*r*r;
}
};
class Rectangle:public Shape {
private:
double w,h;
public:
Rectangle(double x,double y) {
w=x,h=y;
}
virtual double printArea() {
return w*h;
}
};
class Triangle:public Shape {
private:
double w,h;
public:
Triangle(double x,double y) {
w=x,h=y;
}
virtual double printArea() {
return w*h/2;
}
};
double printArea(Shape &x) {
return x.printArea();
}
int main() {
double a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
Circle cir(a);
Rectangle rec(b,c);
Triangle tri(d,e);
cout<<fixed<<setprecision(2)<<"area of circle="<<printArea(cir)<<'\n';
cout<<fixed<<setprecision(2)<<"area of rectangle="<<printArea(rec)<<'\n';
cout<<fixed<<setprecision(2)<<"area of triangle="<<printArea(tri)<<'\n';
return 0;
}以上所述是小編給大家介紹的C++計(jì)算圓形、矩形和三角形的面積,希望對(duì)大家有所幫助。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
基于OpenGL實(shí)現(xiàn)多段Bezier曲線拼接
這篇文章主要為大家詳細(xì)介紹了基于OpenGL實(shí)現(xiàn)多段Bezier曲線拼接,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-04-04
C++簡單五子棋的AI設(shè)計(jì)實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了C++簡單五子棋的AI設(shè)計(jì)實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-09-09
c語言讀取obj文件轉(zhuǎn)換數(shù)據(jù)的小例子
c語言讀取obj文件轉(zhuǎn)換數(shù)據(jù)的小例子,需要的朋友可以參考一下2013-03-03
詳解如何在code block創(chuàng)建一個(gè)C語言的項(xiàng)目
這篇文章主要介紹了詳解如何在code block創(chuàng)建一個(gè)C語言的項(xiàng)目,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12

