C++計算圓形、矩形和三角形的面積
題目描述
運用多態(tài)編寫程序,聲明抽象基類Shape,由它派生出3個派生類: Circle(圓形)、Rectangle(矩形)、Triangle(三角形),用一個函數(shù)printArea()分別輸出以上三者的面積(結(jié)果保留兩位小數(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)站的支持!
相關(guān)文章
c語言讀取obj文件轉(zhuǎn)換數(shù)據(jù)的小例子
c語言讀取obj文件轉(zhuǎn)換數(shù)據(jù)的小例子,需要的朋友可以參考一下2013-03-03
詳解如何在code block創(chuàng)建一個C語言的項目
這篇文章主要介紹了詳解如何在code block創(chuàng)建一個C語言的項目,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2020-12-12

