大家帮忙看一下了,用c#编写(2)定义一个复数类,通过重载运算符:+、-、*、/,直接实现两个复数之间的四则运算。编写一个完整的程序包括测试各种运算符的程序部分。提示:两个复数相
(2) 定义一个复数类,通过重载运算符:+、-、*、/,直接实现两个复数之间的四则运算。编写一个完整的程序包括测试各种运算符的程序部分。
提示:两个复数相乘的计算公式为(a+bi)* (c+di) = (ac-bd) + (ad+bc)i。
两个复数相除的计算公式为(a+bi)/ (c+di) = (ac+bd)/(c*c+d*d) + (bc -ad)/ (c*c+d*d) i。
class Complex
{
public double real;
public double imaginary;
public Complex(double real, double imaginary) //构造函数
{
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博客
阅读题《诺言》的答案信守和尊重一个诺言,或许要比登一座山更难.我一直记得少年时读过的一则异国故事:在 2020-03-30 …
阅读题《诺言》答案诺言信守和尊重一个诺言,或许要比登一座山更难.我一直记得以前读过的一则故事:在一座 2020-03-30 …
事故“三不放过”的原则是什么? 2020-05-28 …
诺言阅读答案诺言信守和尊重一个诺言,或许要比登一座山更难.我一直记得少年时读过的一则异国故事:在一 2020-06-08 …
五年级山东教育出版社暑假作业阅读之一信守和尊重一个诺言,或许要比登一座山更难.我一直记得少年时读过 2020-06-23 …
审议表决应当遵循“集体审查审议、明确发表意见、绝对多数通过,,的原则。( )A.正确B.错误 2020-06-27 …
诺言①守信和尊重一个诺言,或许要比登一座山更难.②我一直记得少年时读过的一则异国故事:在一座城市的 2020-07-03 …
诺言信守和尊重一个诺言,或许要比登一座山更难。我一直记得少年时读过的一则异国故事:在一座城市的冬夜 2020-07-03 …
阅读记载某皇帝功过的四则材料,回答问题。材料一:廿六年,皇帝尽并兼天下诸侯,黔首大安,立号为皇帝。 2020-07-16 …
写出你读过的四则寓言故事谢谢其中你最喜欢的是:原因是:. 2020-07-23 …