编程一小时2023.4.24

1.

#include<iostream>
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.14159*radius*radius;
}
protected:
double radius;
};

class Square:public Shape
{
public:
Square(double s):side(s)
{

}
virtual double area() const
{
return side*side;
}
protected:
double side;
};

class Rectangle:public Shape
{
public:
Rectangle(double w,double h):width(w),height(h)
{

}
virtual double area() const
{
return width*height;
}
protected:
double width,height;
};

class Trapezoid:public Shape
{
public:
Trapezoid(double t,double b,double h):top(t),bottom(b),height(h)
{

}
virtual double area() const
{
return 0.5*(top+bottom)*height;
}
protected:
double top,bottom,height;

};

class Triangle:public Shape
{
public:
Triangle(double w,double h):width(w),height(h)
{

}
virtual double area() const
{
return 0.5*width*height;
}
protected:
double width,height;
};

int main()
{
Circle circle(12.6);
Square square(3.5);
Rectangle rectangle(4.5,8.4);
Trapezoid trapezoid(2.0,4.5,3.2);
Triangle triangle(4.5,8.4);
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;
}

2.

#include<iostream>
#include<iomanip>
using namespace std;
class Shape {
public:
virtual void display() = 0;
};
class Circle :public Shape {
double radium;
public:
Circle(double r) :radium(r) {}
virtual void display();
};
class Rectangle :public Shape {
double lenth, width;
public:
Rectangle(double l, double w) :lenth(l), width(w) {}
virtual void display();
};
class Triangle :public Shape {
double high, bottom;
public:
Triangle(double h, double b) :high(h), bottom(b) {}
virtual void display();
};
void Circle::display() {
cout << fixed << setprecision(2) << 3.1415 * radium * radium << endl;;
}
void Rectangle::display() {
cout << fixed << setprecision(2) << lenth * width << endl;
}
void Triangle::display() {
cout << fixed << setprecision(2) << 0.5 * high * bottom << endl;
}
int main()
{
double radium, high, lenth, width, bottom;
cin >> radium >> lenth >> width >> high >> bottom;
Shape* p[3];
p[0] = new Circle(radium);
p[1] = new Rectangle(lenth, width);
p[2] = new Triangle(high, bottom);
for (int i = 0; i < 3; i++) {
p[i]->display();
delete p[i];
}
}

 

posted @   Verneyyx  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示