YTU-OJ-Problem D: C++習題 虛擬函式-計算圖形面積

kewlgrl發表於2015-07-21

Problem D: C++習題 虛擬函式-計算圖形面積

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 632  Solved: 507
[Submit][Status][Web Board]

Description

編寫一個程式,定義抽象基類Shape,由它派生出5個派生類: Circle(圓形)、Square(正方形)、Rectangle(矩形)、Trapezoid(梯形)、Triangle(三角形)。
用虛擬函式分別計算幾種圖形面積,並求它們之和。
要求用基類指標陣列,使它每一個元素指向一個派生類物件。 

Input

圓的半徑
正方形的邊長
矩形的邊長
梯形的上底和下底,高
三角形的底與高

Output

所有圖形面積之和(結果保留兩位小數)

Sample Input

12.6
3.5
4.5 8.4
2.0 4.5 3.2
4.5 8.4

Sample Output

total of all areas=574.11

HINT

主函式已給定如下,提交時不需要包含,會自動新增到程式尾部

/* C++程式碼 */


int main()

{

    float r,a,b,w1,w2,w,h;

    cout<<fixed<<setprecision(2);

    cin>>r;

    Circle circle(r);

    cin>>a;

    Square square(a);

    cin>>a>>b;

    Rectangle rectangle(a,b);

    cin>>w1>>w2>>h;

    Trapezoid trapezoid(w1,w1,h);

    cin>>w>>h;

    Triangle triangle(w,h);

    Shape *pt[5]= {&circle,&square,&rectangle,&trapezoid,&triangle};

    double areas=0.0;

    for(int i=0; i<5; i++)

        areas=areas+pt[i]->area();

    cout<<"total of all areas="<<areas<<endl;

    return 0;

}

#include<iostream>
#include<cstdio>
#include<iomanip>
using namespace std;
class Shape
{
public:
    virtual double area() const=0;
};
class Circle:public Shape
{
public:
    Circle(double r):radius(r) {}
    virtual double area()const
    {
        return 3.141592*radius*radius;
    }
private:
    double radius;
};
class Square:public Shape
{
public:
    Square(double xx):x(xx) {}
    virtual double area()const
    {
        return x*x;
    }
private:
    double x;
};
class Rectangle:public Shape
{
public:
    Rectangle(double aa,double bb):a(aa),b(bb) {}
    virtual double area()const
    {
        return a*b;
    }
private:
    double a,b;
};
class Trapezoid:public Shape
{
public:
    Trapezoid(double aa,double bb,double h):a1(aa),a2(bb),h0(h) {}
    virtual double area()const
    {
        return (a1+a2)*h0*0.5;
    }
private:
    double h0,a1,a2;
};
class Triangle:public Shape
{
public:
    Triangle(double ww,double hh):w(ww),h(hh) {}
    virtual double area()const
    {
        return 0.5*w*h;
    }
private:
    double w,h;
};

int main()
{
    float r,a,b,w1,w2,w,h;
    cout<<fixed<<setprecision(2);
    cin>>r;
    Circle circle(r);
    cin>>a;
    Square square(a);
    cin>>a>>b;
    Rectangle rectangle(a,b);
    cin>>w1>>w2>>h;
    Trapezoid trapezoid(w1,w1,h);
    cin>>w>>h;
    Triangle triangle(w,h);
    Shape *pt[5]= {&circle,&square,&rectangle,&trapezoid,&triangle};
    double areas=0.0;
    for(int i=0; i<5; i++)
        areas=areas+pt[i]->area();
    cout<<"total of all areas="<<areas<<endl;
    return 0;
}


相關文章