using System;
public class Complex
{
public int Real { get; set; }
public int Imaginary { get; set; }
// 构造函数
public Complex(int real, int imaginary)
{
Real = real;
Imaginary = imaginary;
}
// 重载 + 运算符,用于复数相加
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
// 重载 - 运算符,用于复数相减
public static Complex operator -(Complex c1, Complex c2)
{
return new Complex(c1.Real - c2.Real, c1.Imaginary - c2.Imaginary);
}
// 重载 * 运算符,用于复数相乘
public static Complex operator *(Complex c1, Complex c2)
{
return new Complex(
c1.Real * c2.Real - c1.Imaginary * c2.Imaginary,
c1.Real * c2.Imaginary + c1.Imaginary * c2.Real
);
}
// 重写 ToString 方法,方便输出
public override string ToString()
{
return $"{Real} + {Imaginary}i";
}
}
class Program
{
static void Main()
{
Complex num1 = new Complex(3, 4);
Complex num2 = new Complex(1, 2);
Complex sum = num1 + num2;
Console.WriteLine($"Sum: {sum}");
Complex difference = num1 - num2;
Console.WriteLine($"Difference: {difference}");
Complex product = num1 * num2;
Console.WriteLine($"Product: {product}");
}
}
Complex 类来表示复数,包含两个属性 Real 和 Imaginary 分别表示复数的实部和虚部。+:重载了加法运算符,实现两个复数的相加。-:重载了减法运算符,实现两个复数的相减。*:重载了乘法运算符,实现两个复数的相乘。ToString 方法,以便于将复数对象转换为字符串格式进行输出。Main 方法中创建了两个复数对象,并演示了如何使用重载的运算符进行加、减、乘操作,并输出结果。上一篇:c# int转枚举
下一篇:c# 8.0
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站