using System; ///Complex. This type implements complex numbers with the ///usual arithmetic operations. struct Complex { double re; double im; ///Creates a new complex number. ///The real part of this number. ///The imaginary part of this number. public Complex(double re, double im) {this.re = re; this.im = im;} ///Creates a new complex number with an imaginary part of 0. ///The real part of this number. public Complex(double re) : this(re, 0) {} ///Returns the real part of this number. public double Re { get { return re; } set { re = value; } } ///Returns the imaginary part of this number. public double Im { get { return im; } set { im = value; } } ///Returns a string representation of this number in the form x + yi. ///This method is inherited from System.Object. public override string ToString() { return String.Format("{0:f2}+{1:f2}i", re, im); } ///Checks the equality of two complex numbers. ///This method is inherited from System.Object. ///The object to compare this number with. public override bool Equals(object obj) { return this == (Complex)obj; } ///Returns a hash code for this number. ///This method is inherited from System.Object public override int GetHashCode() { return ((int)re) ^ ((int)im); } ///Adds two complex numbers and returns a new complex number ///with the result public static Complex operator + (Complex x, Complex y) { return new Complex(x.re + y.re, x.im + y.im); } ///Subtracts two complex numbers and returns a new complex number ///with the result public static Complex operator - (Complex x, Complex y) { return new Complex(x.re - y.re, x.im - y.im); } ///Multiplies two complex numbers and returns a new complex number ///with the result public static Complex operator * (Complex x, Complex y) { return new Complex(x.re * y.re - x.im * y.im, x.re * y.im + y.re * x.im); } ///Divides two complex numbers and returns a new complex number ///with the result public static Complex operator / (Complex x, Complex y) { double n = y.re * y.re + y.im * y.im; return new Complex((x.re * y.re + x.im * y.im)/n, (y.re * x.im - x.re * y.im)/n); } ///Compares two complex numbers for equality. public static bool operator == (Complex x, Complex y) { return x.re == y.re && x.im == y.im; } ///Compares two complex numbers for inequality. public static bool operator != (Complex x, Complex y) { return x.re != y.re || x.im != y.im; } ///Converts a complex number to a double value ///by returning the real part of it. public static explicit operator double(Complex x) { return x.re; } ///Converts a double number to a complex number ///by setting the imaginary part to 0. public static implicit operator Complex(double x) { return new Complex(x, 0); } } class Test { public static void Main() { Complex x = 1; Complex y = new Complex(2, 1); Console.WriteLine(x + y); Console.WriteLine(x * y); Console.WriteLine(y / y); Console.WriteLine((double)y); } }