Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Số phức (Complex Numbers) trong C#


Để làm việc VỚI và hiển thị số phức trong C#, bạn cần kiểm tra phần thực và phần ảo.

Số phức như 7+5i được cấu thành từ hai phần: phần thực 7 và phần ảo 5. Ở đây, phần ảo là bội số của i.

Để hiển thị số phức hoàn chỉnh, sử dụng:

public struct Complex

Để cộng hai số phức, bạn cần cộng phần thực và phần ảo:

public static Complex operator +(Complex one, Complex two) { 
    return new Complex(one.real + two.real, one.imaginary + two.imaginary); 
}

Bạn có thể chạy mã sau để làm việc với số phức trong C#.

Ví dụ

using System; 

public struct Complex { 
    public int real; 
    public int imaginary; 
    
    public Complex(int real, int imaginary) { 
        this.real = real; 
        this.imaginary = imaginary; 
    } 
    
    public static Complex operator +(Complex one, Complex two) { 
        return new Complex(one.real + two.real, one.imaginary + two.imaginary); 
    } 
    
    public override string ToString() { 
        return (String.Format("{0} + {1}i", real, imaginary)); 
    } 
} 

class Demo { 
    static void Main() { 
        Complex val1 = new Complex(7, 1); 
        Complex val2 = new Complex(2, 6); 
        // Cộng cả hai 
        Complex res = val1 + val2; 
        Console.WriteLine("Thứ nhất: {0}", val1); 
        Console.WriteLine("Thứ hai: {0}", val2); 
        // hiển thị kết quả 
        Console.WriteLine("Kết quả (Tổng): {0}", res); 
        Console.ReadLine(); 
    } 
}

Kết quả

Thứ nhất: 7 + 1i 
Thứ hai: 2 + 6i 
Kết quả (Tổng): 9 + 7i