How do you define complex numbers in C language?

In the C programming language, structures can be used to define complex numbers. Complex numbers can be represented as the sum of a real part and an imaginary part. Two floating-point variables can be used to represent the real and imaginary parts of a complex number.

Here is an example code that defines a structure for complex numbers.

typedef struct {
    float real;     // 实数部分
    float imaginary;    // 虚数部分
} Complex;

After defining a complex number variable with the above structure, various complex operations can be performed, such as addition, subtraction, multiplication, division, etc.

Here are some sample codes:

#include <stdio.h>

// 定义复数结构体
typedef struct {
    float real;
    float imaginary;
} Complex;

// 复数加法
Complex add(Complex c1, Complex c2) {
    Complex result;
    result.real = c1.real + c2.real;
    result.imaginary = c1.imaginary + c2.imaginary;
    return result;
}

// 复数减法
Complex subtract(Complex c1, Complex c2) {
    Complex result;
    result.real = c1.real - c2.real;
    result.imaginary = c1.imaginary - c2.imaginary;
    return result;
}

int main() {
    Complex c1 = {3.0, 2.0};
    Complex c2 = {1.5, 4.5};

    Complex sum = add(c1, c2);       // 复数相加
    Complex difference = subtract(c1, c2);     // 复数相减

    printf("Sum: %.2f + %.2fi\n", sum.real, sum.imaginary);
    printf("Difference: %.2f + %.2fi\n", difference.real, difference.imaginary);

    return 0;
}

The output is:

Sum: 4.50 + 6.50i
Difference: 1.50 - 2.50i

The code above defines a structure Complex for complex numbers and implements addition and subtraction operations. In the main function, two complex numbers c1 and c2 are defined, then the add and subtract functions are called for addition and subtraction operations, and the results are printed.

bannerAds