溫馨提示×

如何使用C#實現(xiàn)復(fù)數(shù)運算

c#
小樊
107
2024-08-13 08:22:41
欄目: 編程語言

在C#中,可以使用自定義類來表示和操作復(fù)數(shù)。以下是一個簡單的示例代碼,展示了如何定義一個復(fù)數(shù)類,并實現(xiàn)一些基本的復(fù)數(shù)運算:

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的類,表示復(fù)數(shù),并實現(xiàn)了加法、減法、乘法和除法等基本復(fù)數(shù)運算。在Main方法中,我們創(chuàng)建了兩個復(fù)數(shù)對象,并對它們進(jìn)行了加減乘除運算,并輸出結(jié)果。通過這種方式,我們可以使用C#來進(jìn)行復(fù)數(shù)運算。

0