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博客
大家帮忙看一下了,用c#编写(2) 定义一个复数类,通过重载运算符:+、-、*、/,直接实现两个复数之间的四则运算。编写
1个回答
相关问题
-
定义一个复数类,通过重载运算符:+、-、*、/,直接实现两个复数之间的四则运算.
-
用C++编写程序,定义一个复数类,编写程序重载四则运算符和++、--运算符,实现复数的相关运算;
-
(C++高手帮忙)定义一个复数类Complex,重载运算符“-”,使之能用于复数的减法运算.
-
(C++)定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算.
-
1)编写复数类,重载加法+、减法-、乘法*等运算符,其中加法+为友元函数,其他为复数类成员函数 2)设计评
-
考试编程题 求答案!定义一个复数类Complex,重载运算符“+”,使之能用于复数的加法运算。将运算符重载函数重载为类的
-
请编写一个类Complex,定义复数的加法、减法、乘法和除法运算,要求在编写该类时重载这些运算操作符,并重载I/O操作符
-
定义一个复数类,实部和虚部都是整数类型,用成员函数形式重载复数的“+”运算,用友元函数的形式重载 “
-
求两道C++编程题1..设计一个类来实现重载自加运算符的两种形式,即前缀运算符++a和后缀运算符a++2.设计一个表示的
-
定义复数类complex,并使用友元函数实现复数的加法,减法,乘法,所有函数都返回c