大家帮忙看一下了,用c#编写(2) 定义一个复数类,通过重载运算符:+、-、*、/,直接实现两个复数之间的四则运算。编写

1个回答

  • classComplex{public doublereal;public doubleimaginary;public Complex(doublereal, doubleimaginary)//构造函数{this.real = real;this.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);}//声明重载运算符(/),将两个复数对象相除,返回复数类型public static Complex operator / (Complex c1, Complex c2){double cd = c2.real * c2.real + c2.imaginary * c2.imaginary ;return new Complex((c1.real * c2.real + c1.imaginary * c2.imaginary) / cd, (c1.imaginary * c2.real -c1.real*c2.imaginary)/cd);}//重载ToString() 方法,以传统格式显示复数public override string ToString(){return (String.Format("{0} + {1}i", real, imaginary));}}class TestComplex{static void Main(){Complex num1 = new Complex(2, 3);Complex num2 = new Complex(3, 4);Complex sum = num1 + num2; //重载加运算符添加复数对象Complex sub = num1 - num2; //重载减运算符添加复数对象Complex multiplication = num1 * num2;//重载减运算符添加复数对象Complex division = num1 / num2;//重载减运算符添加复数对象//重载ToString方法输出复数的加减乘除Console.WriteLine("第一个复数:{0}", num1);Console.WriteLine("第二个复数: {0}", num2);Console.WriteLine("复数和: {0}", sum);Console.WriteLine("复数差: {0}", sub);Console.WriteLine("复数积: {0}", multiplication);Console.WriteLine("复数商: {0}", division);}}请看我的博客danyaody 163博客