C# 圆柱体类:计算体积和表面积
下面是 Cylinder 类的代码:
using System;
class Cylinder
{
private double radius;
private double height;
public Cylinder(double r, double h)
{
radius = r;
height = h;
}
public double Volume()
{
return Math.PI * radius * radius * height;
}
public double Area()
{
return 2 * Math.PI * radius * height + 2 * Math.PI * radius * radius;
}
}
下面是 Test 类的代码:
using System;
class Test
{
static void Main()
{
Cylinder c = new Cylinder(3.0, 5.0);
Console.WriteLine('Volume: ' + c.Volume());
Console.WriteLine('Area: ' + c.Area());
}
}
在这个程序中,我们首先定义了一个叫做 Cylinder 的类,它有两个私有字段 radius 和 height,分别表示圆柱体的底面半径和高。我们使用构造方法对对象进行构造,然后定义了两个方法 Volume 和 Area 来计算圆柱体的体积和表面积。在 Test 类中,我们创建了一个 Cylinder 对象,然后调用它的 Volume 和 Area 方法来输出圆柱体的体积和表面积。
原文地址: https://www.cveoy.top/t/topic/nnQ0 著作权归作者所有。请勿转载和采集!