Để làm việc với và hiển thị số phức trong C #, bạn cần kiểm tra các giá trị thực và ảo.
Một số phức như 7 + 5i được tạo thành từ hai phần, một phần thực 7 và một phần ảo 5. Ở đây, phần ảo là bội số của i.
Để hiển thị các số đầy đủ, hãy sử dụng -
public struct Complex
Để thêm cả số phức, bạn cần thêm 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ể thử chạy đoạn mã sau để làm việc với các 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);
// Add both of them
Complex res = val1 + val2;
Console.WriteLine("First: {0}", val1);
Console.WriteLine("Second: {0}", val2);
// display the result
Console.WriteLine("Result (Sum): {0}", res);
Console.ReadLine();
}
} Đầu ra
First: 7 + 1i Second: 2 + 6i Result (Sum): 9 + 7i