用C#设计一个复数类,重载运算符,实现复数的加法和乘法运算。并实现复数到浮点数的强制类型转换。 设计Main()函数,使用此复数类。
时间: 2023-11-22 18:53:42 浏览: 154
下面是一个用C#设计的复数类,包括重载运算符,实现复数的加法和乘法运算,并实现复数到浮点数的强制类型转换:
```csharp
using System;
namespace ComplexNumber
{
class Complex
{
private double real;
private double imag;
public Complex(double real, double imag)
{
this.real = real;
this.imag = imag;
}
public static Complex operator +(Complex a, Complex b)
{
return new Complex(a.real + b.real, a.imag + b.imag);
}
public static Complex operator *(Complex a, Complex b)
{
return new Complex(a.real * b.real - a.imag * b.imag, a.real * b.imag + a.imag * b.real);
}
public static explicit operator double(Complex a)
{
return Math.Sqrt(a.real * a.real + a.imag * a.imag);
}
public override string ToString()
{
return string.Format("{0} + {1}i", real, imag);
}
}
class Program
{
static void Main(string[] args)
{
Complex a = new Complex(1, 2);
Complex b = new Complex(3, 4);
Complex c = a + b;
Console.WriteLine("a + b = {0}", c);
Complex d = a * b;
Console.WriteLine("a * b = {0}", d);
double e = (double)a;
Console.WriteLine("a = {0}, |a| = {1}", a, e);
Console.ReadKey();
}
}
}
```
在Main()函数中,我们创建了两个复数对象a和b,然后分别进行加法运算和乘法运算,并输出结果。我们还将复数a强制类型转换为浮点数,并输出其模长。
阅读全文