Table of contents Home page
using System; public struct ComplexNumber : IComparable { private double real; private double imaginary; public ComplexNumber(double real, double imaginary) { this.real = real; this.imaginary = imaginary; } public int CompareTo(object o) { // this is greater than o if |this| is greater than |o| // this is less than o if |this| is less than |o| // this equals o if |this| equals |o| ComplexNumber cn = (ComplexNumber)o; double diff = Math.Sqrt(this.real * this.real + this.imaginary * this.imaginary) - Math.Sqrt(cn.real * cn.real + cn.imaginary * cn.imaginary); if (diff > 0) { return 1; } else if (diff < 0) { return -1; } else { return 0; } } } public class Program { public static void Main(string[] args) { ComplexNumber n1 = new ComplexNumber(5, -6); ComplexNumber n2 = new ComplexNumber(13, 4); Console.WriteLine(n1.CompareTo(n2)); Console.WriteLine(n2.CompareTo(n1)); Console.WriteLine(n1.CompareTo(n1)); Console.ReadKey(); } }