亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

如何使用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
大方县| 涿州市| 左云县| 改则县| 革吉县| 阳西县| 海安县| 长阳| 得荣县| 确山县| 河西区| 淮阳县| 乌拉特中旗| 静海县| 南京市| 潮安县| 石渠县| 北京市| 苍山县| 罗山县| 博白县| 龙山县| 宣汉县| 阆中市| 麻城市| 普陀区| 公主岭市| 阿尔山市| 灯塔市| 沿河| 乐陵市| 长兴县| 乌拉特中旗| 长宁区| 长治市| 宣汉县| 龙南县| 桦川县| 淳化县| 新邵县| 西藏|