Cho là hai số phức có dạng a1 + ib1 và a2 + ib2, nhiệm vụ là cộng hai số phức này.
Số phức là những số có thể được biểu diễn dưới dạng “a + ib” trong đó “a” và “b” là các số thực và i là số ảo là nghiệm của biểu thức 𝑥 2 =−1 là không số thực thỏa mãn phương trình, đó là lý do tại sao nó được gọi là số ảo.
Đầu vào
a1 = 3, b1 = 8 a2 = 5, b2 = 2
Đầu ra
Complex number 1: 3 + i8 Complex number 2: 5 + i2 Sum of the complex numbers: 8 + i10
Giải thích
(3+i8) + (5+i2) = (3+5) + i(8+2) = 8 + i10
Đầu vào
a1 = 5, b1 = 3 a2 = 2, b2 = 2
Đầu ra
Complex number 1: 5 + i3 Complex number 2: 2 + i2 Sum of the complex numbers: 7 + i5
Giải thích
(5+i3) + (2+i2) = (5+2) + i(3+2) = 7 + i5
Phương pháp tiếp cận được sử dụng dưới đây như sau để giải quyết vấn đề
-
Khai báo một cấu trúc để lưu trữ số thực và số ảo.
-
Lấy đầu vào và thêm các số thực và số ảo của tất cả các số phức.
Thuật toán
Start
Decalre a struct complexnum with following elements
1. real
2. img
In function complexnum sumcomplex(complexnum a, complexnum b)
Step 1→ Declare a signature struct complexnum c
Step 2→ Set c.real as a.real + b.real
Step 3→ Set c.img as a.img + b.img
Step 4→ Return c
In function int main()
Step 1→ Declare and initialize complexnum a = {1, 2} and b = {4, 5}
Step 2→ Declare and set complexnum c as sumcomplex(a, b)
Step 3→ Print the first complex number
Step 4→ Print the second complex number
Step 5→ Print the sum of both in c.real, c.img
Stop Ví dụ
#include <stdio.h>
//structure for storing the real and imaginery
//values of complex number
struct complexnum{
int real, img;
};
complexnum sumcomplex(complexnum a, complexnum b){
struct complexnum c;
//Adding up two complex numbers
c.real = a.real + b.real;
c.img = a.img + b.img;
return c;
}
int main(){
struct complexnum a = {1, 2};
struct complexnum b = {4, 5};
struct complexnum c = sumcomplex(a, b);
printf("Complex number 1: %d + i%d\n", a.real, a.img);
printf("Complex number 2: %d + i%d\n", b.real, b.img);
printf("Sum of the complex numbers: %d + i%d\n", c.real, c.img);
return 0;
} Đầu ra
Nếu chạy đoạn mã trên, nó sẽ tạo ra kết quả sau -
Complex number 1: 1 + i2 Complex number 2: 4 + i5 Sum of the complex numbers: 5 + i7