按照以下要求设计接口lArea、长方形类Rectangle、正方形类Square、圆形类Circle,最终在主函数中输出长方形、正方形及圆形面积。 1.接口IArea,包含:计算面积的方法double Area(); 2.类Rectangle、类Square、类Circle继承接口,包含: ①自动属性; ②构造函数(能判断对应参数的合理性(如: x>0)); ③实现计算面积的方法Area(); 3.主函数中,创建三个对象(如下: ),分别调用方法Area(),输出三种图形的面积。IArear = new Rectangle(3, 5); //Rectangle r = new Rectangle(3, 5) Console. WriteLine("长方形的面积为: {0:0. 00) ",r. Area0); IAreas = nCw Square(3) ; Console. WriteLine(正方形的面积为: {0:0.00},s. Area() ; IArea c = new Circle(2) ; Console. WriteLine("圆形的面积为: {0:0. 00}”,c. Area(): >输出样例: 长方形的面积为:15.00正方形的面积为:9.00圆形的面积为:12.57。使用c sharp编写
时间: 2024-02-01 08:13:56 浏览: 119
以下是代码实现:
```csharp
using System;
interface IArea
{
double Area();
}
class Rectangle : IArea
{
private double length;
private double width;
public Rectangle(double l, double w)
{
if (l > 0 && w > 0)
{
length = l;
width = w;
}
else
{
throw new ArgumentException("Length and width must be greater than 0.");
}
}
public double Area()
{
return length * width;
}
}
class Square : IArea
{
private double side;
public Square(double s)
{
if (s > 0)
{
side = s;
}
else
{
throw new ArgumentException("Side must be greater than 0.");
}
}
public double Area()
{
return side * side;
}
}
class Circle : IArea
{
private double radius;
public Circle(double r)
{
if (r > 0)
{
radius = r;
}
else
{
throw new ArgumentException("Radius must be greater than 0.");
}
}
public double Area()
{
return Math.PI * radius * radius;
}
}
class Program
{
static void Main(string[] args)
{
IArea r = new Rectangle(3, 5);
Console.WriteLine("长方形的面积为: {0:0.00}", r.Area());
IArea s = new Square(3);
Console.WriteLine("正方形的面积为: {0:0.00}", s.Area());
IArea c = new Circle(2);
Console.WriteLine("圆形的面积为: {0:0.00}", c.Area());
}
}
```
输出结果:
```
长方形的面积为: 15.00
正方形的面积为: 9.00
圆形的面积为: 12.57
```
阅读全文