使用C#利用多态性写一个可以计算多种立体图形(立方体,球体,三棱锥,圆柱体)的体积和表面积,
时间: 2023-07-16 12:16:07 浏览: 110
好的,以下是一个示例代码:
```
using System;
namespace GeometryCalculator
{
class Program
{
static void Main(string[] args)
{
// 创建各种立体图形的实例
Cube cube = new Cube(5);
Sphere sphere = new Sphere(3);
Pyramid pyramid = new Pyramid(4, 6);
Cylinder cylinder = new Cylinder(2, 5);
// 计算并输出各种立体图形的体积和表面积
Console.WriteLine("Cube: Volume={0}, Surface Area={1}", cube.Volume(), cube.SurfaceArea());
Console.WriteLine("Sphere: Volume={0}, Surface Area={1}", sphere.Volume(), sphere.SurfaceArea());
Console.WriteLine("Pyramid: Volume={0}, Surface Area={1}", pyramid.Volume(), pyramid.SurfaceArea());
Console.WriteLine("Cylinder: Volume={0}, Surface Area={1}", cylinder.Volume(), cylinder.SurfaceArea());
Console.ReadLine();
}
}
// 抽象的立体图形类
abstract class Shape
{
// 计算体积的抽象方法
public abstract double Volume();
// 计算表面积的抽象方法
public abstract double SurfaceArea();
}
// 立方体类
class Cube : Shape
{
private double sideLength;
public Cube(double sideLength)
{
this.sideLength = sideLength;
}
public override double Volume()
{
return Math.Pow(sideLength, 3);
}
public override double SurfaceArea()
{
return 6 * Math.Pow(sideLength, 2);
}
}
// 球体类
class Sphere : Shape
{
private double radius;
public Sphere(double radius)
{
this.radius = radius;
}
public override double Volume()
{
return (4 / 3.0) * Math.PI * Math.Pow(radius, 3);
}
public override double SurfaceArea()
{
return 4 * Math.PI * Math.Pow(radius, 2);
}
}
// 三棱锥类
class Pyramid : Shape
{
private double baseLength;
private double height;
public Pyramid(double baseLength, double height)
{
this.baseLength = baseLength;
this.height = height;
}
public override double Volume()
{
return (1 / 3.0) * Math.Pow(baseLength, 2) * height;
}
public override double SurfaceArea()
{
double slantHeight = Math.Sqrt(Math.Pow(baseLength / 2.0, 2) + Math.Pow(height, 2));
return (baseLength * slantHeight) + (2 * Math.Pow(baseLength / 2.0, 2));
}
}
// 圆柱体类
class Cylinder : Shape
{
private double radius;
private double height;
public Cylinder(double radius, double height)
{
this.radius = radius;
this.height = height;
}
public override double Volume()
{
return Math.PI * Math.Pow(radius, 2) * height;
}
public override double SurfaceArea()
{
return (2 * Math.PI * radius * height) + (2 * Math.PI * Math.Pow(radius, 2));
}
}
}
```
以上代码中,我们定义了一个抽象的立体图形类 `Shape`,其中包含了两个抽象方法 `Volume()` 和 `SurfaceArea()`,用于计算体积和表面积。然后我们分别定义了立方体类 `Cube`、球体类 `Sphere`、三棱锥类 `Pyramid` 和圆柱体类 `Cylinder`,这些类都继承自 `Shape` 类,并分别实现了其抽象方法。在 `Main` 方法中,我们创建了各种立体图形的实例,并调用了它们的 `Volume()` 和 `SurfaceArea()` 方法来计算它们的体积和表面积,并输出结果。
阅读全文