用c#定义一个矩形类,计算矩形的面积和周长
时间: 2024-03-11 07:19:24 浏览: 118
以下是用 C# 定义一个矩形类,并计算矩形的面积和周长的示例代码:
```csharp
using System;
class Rectangle
{
private double length;
private double width;
public Rectangle(double length, double width)
{
this.length = length;
this.width = width;
}
public double GetArea()
{
return length * width;
}
public double GetPerimeter()
{
return 2 * (length + width);
}
}
class Program
{
static void Main(string[] args)
{
Rectangle rect = new Rectangle(5.0, 3.0);
Console.WriteLine("矩形的面积为: {0}", rect.GetArea());
Console.WriteLine("矩形的周长为: {0}", rect.GetPerimeter());
}
}
```
运行结果为:
```
矩形的面积为: 15
矩形的周长为: 16
```
相关问题
用c#定义一个矩形类,计算矩形的面积和周长,矩形的长和宽由输入
可以通过以下代码定义一个矩形类,其中包含长(length)和宽(width)属性,以及计算面积(CalculateArea)和周长(CalculatePerimeter)的方法。
```csharp
class Rectangle {
public double Length { get; set; }
public double Width { get; set; }
public double CalculateArea() {
return Length * Width;
}
public double CalculatePerimeter() {
return 2 * (Length + Width);
}
}
```
接下来可以使用以下代码创建一个矩形对象并输入长和宽,然后调用该对象的方法计算面积和周长。
```csharp
Rectangle rect = new Rectangle();
Console.WriteLine("Enter length:");
rect.Length = double.Parse(Console.ReadLine());
Console.WriteLine("Enter width:");
rect.Width = double.Parse(Console.ReadLine());
double area = rect.CalculateArea();
double perimeter = rect.CalculatePerimeter();
Console.WriteLine("Area: " + area);
Console.WriteLine("Perimeter: " + perimeter);
```
php定义一个矩形类rectangle,c#定义一个类圆Circle或者定义一个矩形类Rectangle,分别计算它们的周长和面积....
PHP定义一个矩形类Rectangle:
```php
class Rectangle {
private $length;
private $width;
public function __construct($length, $width) {
$this->length = $length;
$this->width = $width;
}
public function getArea() {
return $this->length * $this->width;
}
public function getPerimeter() {
return 2 * ($this->length + $this->width);
}
}
```
C#定义一个类圆Circle:
```csharp
class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double GetArea() {
return Math.PI * radius * radius;
}
public double GetPerimeter() {
return 2 * Math.PI * radius;
}
}
```
C#定义一个矩形类Rectangle:
```csharp
class Rectangle {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double GetArea() {
return length * width;
}
public double GetPerimeter() {
return 2 * (length + width);
}
}
```
以上是计算矩形和圆的面积和周长的示例代码。