在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#來進行復數運算。