91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

如何使用C#實現復數運算

c#
小樊
109
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
明水县| 辽阳市| 德钦县| 定结县| 阿克陶县| 子洲县| 来宾市| 普宁市| 吴江市| 离岛区| 长葛市| 临沧市| 靖州| 池州市| 康马县| 长乐市| 新乡县| 兴宁市| 麦盖提县| 左权县| 新建县| 龙山县| 咸丰县| 华蓥市| 江川县| 台湾省| 九龙坡区| 兴安县| 团风县| 平度市| 青岛市| 凤城市| 霍城县| 宜宾县| 文成县| 明星| 江北区| 临湘市| 洛扎县| 军事| 汝南县|