中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

如何使用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
固镇县| 乐业县| 秀山| 延安市| 合阳县| 西充县| 资阳市| 屏山县| 东乡县| 阿克| 澎湖县| 城口县| 青浦区| 西宁市| 淮安市| 肃北| 扬州市| 吉隆县| 青浦区| 渝中区| 东城区| 江山市| 莱芜市| 和平县| 民权县| 南漳县| 黎平县| 武穴市| 六盘水市| 巫溪县| 湖南省| 德安县| 凉城县| 民和| 年辖:市辖区| 府谷县| 揭西县| 拜泉县| 惠水县| 牡丹江市| 东城区|