温馨提示×

如何使用C#实现复数运算

c#
小樊
91
2024-08-13 08:22:41
栏目: 编程语言

在C#中,可以使用自定义类来表示和操作复数。以下是一个简单的示例代码,展示了如何定义一个复数类,并实现一些基本的复数运算:

using System;

public class Complex
{
    public double Real { get; set; }
    public double Imaginary { get; set; }

    public Complex(double real, double imaginary)
    {
        Real = real;
        Imaginary = imaginary;
    }

    public Complex Add(Complex other)
    {
        return new Complex(Real + other.Real, Imaginary + other.Imaginary);
    }

    public Complex Subtract(Complex other)
    {
        return new Complex(Real - other.Real, Imaginary - other.Imaginary);
    }

    public Complex Multiply(Complex other)
    {
        double newReal = Real * other.Real - Imaginary * other.Imaginary;
        double newImaginary = Real * other.Imaginary + Imaginary * other.Real;
        return new Complex(newReal, newImaginary);
    }

    public Complex Divide(Complex other)
    {
        double denominator = other.Real * other.Real + other.Imaginary * other.Imaginary;
        double newReal = (Real * other.Real + Imaginary * other.Imaginary) / denominator;
        double newImaginary = (Imaginary * other.Real - Real * other.Imaginary) / denominator;
        return new Complex(newReal, newImaginary);
    }

    public override string ToString()
    {
        return $"{Real} + {Imaginary}i";
    }
}

class Program
{
    static void Main()
    {
        Complex c1 = new Complex(3, 4);
        Complex c2 = new Complex(2, 1);

        Complex sum = c1.Add(c2);
        Complex difference = c1.Subtract(c2);
        Complex product = c1.Multiply(c2);
        Complex quotient = c1.Divide(c2);

        Console.WriteLine($"Sum: {sum}");
        Console.WriteLine($"Difference: {difference}");
        Console.WriteLine($"Product: {product}");
        Console.WriteLine($"Quotient: {quotient}");
    }
}

在这个示例中,我们定义了一个名为Complex的类,表示复数,并实现了加法、减法、乘法和除法等基本复数运算。在Main方法中,我们创建了两个复数对象,并对它们进行了加减乘除运算,并输出结果。通过这种方式,我们可以使用C#来进行复数运算。

0