Cho 2 số phức a1+ib1 và a2+ib2. Tính tổng: (a1+a2) + i(b1+b2).
Ví dụ
Đầu vào - a1=3, b1=8; a2=5, b2=2
Đầu ra - Tổng: 8 + i10
Đầu vào - a1=5, b1=3; a2=2, b2=2
Đầu ra - Tổng: 7 + i5
Phương pháp
- Định nghĩa struct
Complexvới real, img - Hàm
sumComplex(a, b)trả về struct mới với real = a.real+b.real, img = a.img+b.img
Chương trình mẫu
#include <stdio.h>
struct Complex {
int real, img;
};
struct Complex sumComplex(struct Complex a, struct Complex b) {
struct Complex c;
c.real = a.real + b.real;
c.img = a.img + b.img;
return c;
}
int main() {
struct Complex a = {1, 2};
struct Complex b = {4, 5};
struct Complex c = sumComplex(a, b);
printf("Số phức 1: %d + i%d\n", a.real, a.img);
printf("Số phức 2: %d + i%d\n", b.real, b.img);
printf("Tổng: %d + i%d\n", c.real, c.img);
return 0;
}
Kết quả
Số phức 1: 1 + i2 Số phức 2: 4 + i5 Tổng: 5 + i7