c#实现复数加减运算代码
时间: 2024-10-14 19:03:09 浏览: 45
C#中实现复数的加减运算
在C#中,你可以创建一个名为`ComplexNumber`的自定义类来表示复数,并提供加法和减法的方法。下面是一个简单的示例:
```csharp
public class ComplexNumber
{
public double Real { get; set; }
public double Imaginary { get; set; }
// 构造函数
public ComplexNumber(double real = 0, double imaginary = 0)
{
Real = real;
Imaginary = imaginary;
}
// 加法操作
public static ComplexNumber Add(ComplexNumber a, ComplexNumber b)
{
return new ComplexNumber(a.Real + b.Real, a.Imaginary + b.Imaginary);
}
// 减法操作
public static ComplexNumber Subtract(ComplexNumber a, ComplexNumber b)
{
return new ComplexNumber(a.Real - b.Real, a.Imaginary - b.Imaginary);
}
// 打印复数
public override string ToString()
{
return $"{Real} + {Imaginary}i";
}
}
// 使用示例
public void Main()
{
ComplexNumber num1 = new ComplexNumber(2, 3);
ComplexNumber num2 = new ComplexNumber(4, 5);
ComplexNumber sum = ComplexNumber.Add(num1, num2);
Console.WriteLine($"Sum: {sum}");
ComplexNumber difference = ComplexNumber.Subtract(num1, num2);
Console.WriteLine($"Difference: {difference}");
}
```
在这个例子中,`ComplexNumber`类有两个属性分别代表实部和虚部,`Add`和`Subtract`方法用于执行复数的加减运算。`ToString`方法则是为了方便打印出复数。
阅读全文