C++計算圓形、矩形和三角形的面積
題目描述
運用多態(tài)編寫程序,聲明抽象基類Shape,由它派生出3個派生類: Circle(圓形)、Rectangle(矩形)、Triangle(三角形),用一個函數(shù)printArea()分別輸出以上三者的面積(結果保留兩位小數(shù)),3個圖形的數(shù)據(jù)在定義對象時給定。
輸入
圓的半徑 矩形的邊長 三角形的底與高
輸出
圓的面積
矩形的面積
三角形的面積
注意:每一行后有回車符
樣例輸入
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
代碼實現(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++計算圓形、矩形和三角形的面積,希望對大家有所幫助。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
C++中的三種繼承public,protected,private詳細解析
我們已經(jīng)知道,在基類以private方式被繼承時,其public和protected成員在子類中變?yōu)閜rivate成員。然而某些情況下,需要在子類中將一個或多個繼承的成員恢復其在基類中的訪問權限2013-09-09