早教吧 育儿知识 作业答案 考试题库 百科 知识分享

大家帮忙看一下了,用c#编写(2)定义一个复数类,通过重载运算符:+、-、*、/,直接实现两个复数之间的四则运算。编写一个完整的程序包括测试各种运算符的程序部分。提示:两个复数相

题目详情
大家帮忙看一下了,用c#编写
(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博客

看了 大家帮忙看一下了,用c#编写...的网友还看了以下: