用c#定义描述复数的类,并实现复数的输入和输出。设计三个方法分别完成复数的加、减和乘法运算。请包含适合于入口点的静态 "Main" 方法
时间: 2024-10-26 12:03:01 浏览: 40
在 C# 中,我们可以定义一个名为 `ComplexNumber` 的类来表示复数,并提供适当的属性和方法来进行输入、输出以及基本的数学运算。下面是一个简单的实现示例:
```csharp
using System;
public class ComplexNumber
{
// 定义复数的实部和虚部
public double Real { get; set; }
public double Imaginary { get; set; }
// 构造函数接受实部和虚部作为参数
public ComplexNumber(double real, double imaginary)
{
Real = real;
Imaginary = imaginary;
}
// 方法:字符串输出复数
public override string ToString()
{
return $"({Real} + {Imaginary}i)";
}
// 方法:两个复数相加
public ComplexNumber Add(ComplexNumber other)
{
return new ComplexNumber(Real + other.Real, Imaginary + other.Imaginary);
}
// 方法:两个复数相减
public ComplexNumber Subtract(ComplexNumber other)
{
return new ComplexNumber(Real - other.Real, Imaginary - other.Imaginary);
}
// 方法:两个复数相乘
public ComplexNumber Multiply(ComplexNumber other)
{
double realProduct = Real * other.Real - Imaginary * other.Imaginary;
double imaginaryProduct = Real * other.Imaginary + Imaginary * other.Real;
return new ComplexNumber(realProduct, imaginaryProduct);
}
// 入口点:静态 Main 方法
public static void Main(string[] args)
{
// 示例复数操作
ComplexNumber num1 = new ComplexNumber(3, 4); // 复数 3 + 4i
ComplexNumber num2 = new ComplexNumber(1, 2); // 复数 1 + 2i
Console.WriteLine($"第一个复数: {num1}");
Console.WriteLine($"第二个复数: {num2}");
ComplexNumber sum = num1.Add(num2);
Console.WriteLine($"两数之和: {sum}");
ComplexNumber difference = num1.Subtract(num2);
Console.WriteLine($"两数之差: {difference}");
ComplexNumber product = num1.Multiply(num2);
Console.WriteLine($"两数之积: {product}");
阅读全文