简体   繁体   中英

Create class Complex number in C#

I tried to create class Complex number in C# with two different constructor, the first constructor takes real part and imaginary part, the second constructor takes module and argument.

public class Complex
{
    public Complex() { }

    private Complex(double _re, double _im)
    {
        re = _re;
        im = _im;
    }

    public static double Complex_FromCartesian(double _re, double _im)
    {
        return new Complex(_re, _im);
    }

    public static double Complex_FromPolar(double _mod, double _arg)
    {
        var _re = _mod * Math.Cos(_arg);
        var _im = _mod * Math.Sin(_arg);
        return new Complex(_re, _im);
    }

    public static Complex operator +(Complex num1, Complex num2)
    {
        return new Complex(num1.re + num2.re, num2.im + num2.im);
    }

    public static Complex operator -(Complex num1, Complex num2)
    {
        return new Complex(num1.re - num2.re, num2.im - num2.im);
    }

    public double Re { get; set; }
    public double Im { get; set; }

    private double re, im;
}

}

but I got the same error in both constructors
在此输入图像描述
How to fix that?

Your method returns a double but you're trying to return a Complex type

Change:

public static double Complex_FromCartesian(double _re, double _im)
{
    return new Complex(_re, _im);
}

To:

public static Complex Complex_FromCartesian(double _re, double _im)
{
    return new Complex(_re, _im);
}

将该方法的返回类型更改为Complex

You cant return Complex when double is expected.

public static Complex Complex_FromCartesian(double _re, double _im)
{
   return new Complex(_re, _im);
}

Your constructor is fine. The problem is that you've specified a return type of double and you're returning a class of type "Complex".

This error occurs when the data types mismatch. It is expecting "complex" datatype and you are telling it is double. Change double to complex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM