日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++計算圓形、矩形和三角形的面積_C 語言

作者:一條自私的魚 ? 更新時間: 2022-03-22 編程語言

題目描述

運用多態編寫程序,聲明抽象基類Shape,由它派生出3個派生類: Circle(圓形)、Rectangle(矩形)、Triangle(三角形),用一個函數printArea()分別輸出以上三者的面積(結果保留兩位小數),3個圖形的數據在定義對象時給定。

輸入

圓的半徑 矩形的邊長 三角形的底與高

輸出

圓的面積

矩形的面積

三角形的面積

注意:每一行后有回車符

樣例輸入

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

代碼實現

#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;
}

原文鏈接:https://blog.csdn.net/qq_44343213/article/details/122251497

欄目分類
最近更新