Thứ Tư, 21 Tháng Hai 2024
Trang chủTranslateC/C++ TutorialsThe program adds and subtracts two complex numbers in C/C++

The program adds and subtracts two complex numbers in C/C++

The program adds and subtracts two complex numbers in C/C++.

Program to add and subtract two complex numbers

. In C/C++ programming, to perform operations on complex numbers, it is necessary to create a custom data type for complex numbers. In doing so, the addition and subtraction of two complex numbers are carried out by performing addition and subtraction operations on the real and imaginary parts of the numbers.

To define a data type for complex numbers, the struct structure is used in C/C++. The struct structure allows the storage of different data components within a single data type.

Here is an example of how to define a data type for complex numbers and perform addition and subtraction of two complex numbers in C/C++:

#include <iostream>

using namespace std;

// Define the data type for complex numbers
struct Complex
{
    float real; // Real part
    float imag; // Imaginary part
};

// Function to add two complex numbers
Complex add(Complex a, Complex b)
{
    Complex res;
    res.real = a.real + b.real;
    res.imag = a.imag + b.imag;
    return res;
}

// Function to subtract two complex numbers
Complex sub(Complex a, Complex b)
{
    Complex res;
    res.real = a.real - b.real;
    res.imag = a.imag - b.imag;
    return res;
}

int main()
{
    // Initialize two complex numbers
    Complex num1, num2;
    num1.real = 2;
    num1.imag = 3;
    num2.real = 1;
    num2.imag = 2;

    // Calculate the sum of two complex numbers
    Complex sum = add(num1, num2);
    cout << "Sum of two complex numbers: " << sum.real << " + " << sum.imag << "i" << endl;

    // Calculate the difference of two complex numbers
    Complex diff = sub(num1, num2);
    cout << "Difference of two complex numbers: " << diff.real << " + " << diff.imag << "i" << endl;

    return 0;
}

When the program is run, the result will be:

Sum of two complex numbers: 3 + 5i
Difference of two complex numbers: 1 + 1i

In this output, the real and imaginary parts of the complex numbers are displayed. The addition and subtraction operations are performed by adding and subtracting the real and imaginary parts of the two complex numbers, respectively.

5 1 Bỏ phiếu bình chọn
Xếp hạng bài viết
BÀI VIẾT LIÊN QUAN
Đăng ký nhận thông báo
Thông báo email khi
guest
0 Bình luận
Không thể gửi email
Phản hồi nội tuyến

NÊN ĐỌC THÊM

Bạn muốn tìm kiếm gì?

Dịch vụ code thuê

TUICOCACH.COM NHẬN ĐẶT TEXTLINK, BANNER, GP
0
Giáo sư! có thể ném gạch bên dưới nhé!x