简体   繁体   English

在C#中创建类复数

[英]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. 我尝试用两个不同的构造函数在C#中创建类复数,第一个构造函数采用实部和虚部,第二个构造函数采用模块和参数。

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 您的方法返回一个double但您尝试返回Complex类型

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. 当双重预期时,你不能返回Complex

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". 问题是你已经指定了double的返回类型,并且你正在返回一个类型为“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 双重变为复杂

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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