设计3种三角形面积计算的重载方法,并在主函数中分别调用
时间: 2025-01-06 07:50:03 浏览: 3
在C#中,我们可以设计三个重载(Overload)的方法来计算不同类型的三角形面积,比如基础三角形、等腰三角形以及直角三角形。每个方法接收不同的参数,以便根据特定类型提供相应的计算。
1. 基础三角形(只知道底和高):
```csharp
public double CalculateTriangleArea(double baseLength, double height)
{
return 0.5 * baseLength * height;
}
```
2. 等腰三角形(只知道两边相等的边长和顶角或底角):
```csharp
// 如果知道两等边a和b,夹角θ (使用角度制)
public double CalculateEquilateralTriangleArea(double side)
{
double s = side / 2; // 半周长
double area = Math.Sqrt(3) * Math.Pow(s, 2);
return area;
}
// 如果知道两等边a和b,其中一个锐角A (使用弧度制)
public double CalculateIsoscelesTriangleArea(double side, double angleInRadians)
{
double sinTheta = Math.Sin(angleInRadians);
double area = side * side * sinTheta / 2;
return area;
}
```
3. 直角三角形(知道两条直角边的长度):
```csharp
public double CalculateRightAngleTriangleArea(double a, double b)
{
if (a == 0 || b == 0) throw new ArgumentException("Both sides must be non-zero for a right triangle.");
return 0.5 * a * b;
}
```
在主函数中,你可以这样调用这些方法:
```csharp
static void Main(string[] args)
{
Console.WriteLine("Enter details for a basic triangle:");
double baseLength = double.Parse(Console.ReadLine());
double height = double.Parse(Console.ReadLine());
double basicArea = CalculateTriangleArea(baseLength, height);
Console.WriteLine($"Basic triangle area: {basicArea}");
Console.WriteLine("\nEnter details for an equilateral triangle:");
double equilateralSide = double.Parse(Console.ReadLine());
double equilateralArea = CalculateEquilateralTriangleArea(equilateralSide);
Console.WriteLine($"Equilateral triangle area: {equilateralArea}");
Console.WriteLine("\nEnter details for a right-angled triangle:");
double side1 = double.Parse(Console.ReadLine());
double side2 = double.Parse(Console.ReadLine());
double rightAngleArea = CalculateRightAngleTriangleArea(side1, side2);
Console.WriteLine($"Right-angled triangle area: {rightAngleArea}");
Console.ReadLine();
}
```
阅读全文