c语言

C语言如何处理复数的浮点运算

小亿
92
2024-04-28 16:47:44
栏目: 编程语言

在C语言中,可以使用结构体来表示复数,并定义相应的运算函数来处理复数的浮点运算。以下是一个简单的示例代码:

#include <stdio.h>

typedef struct {
    double real;
    double imag;
} Complex;

Complex add(Complex c1, Complex c2) {
    Complex result;
    result.real = c1.real + c2.real;
    result.imag = c1.imag + c2.imag;
    return result;
}

Complex subtract(Complex c1, Complex c2) {
    Complex result;
    result.real = c1.real - c2.real;
    result.imag = c1.imag - c2.imag;
    return result;
}

Complex multiply(Complex c1, Complex c2) {
    Complex result;
    result.real = c1.real * c2.real - c1.imag * c2.imag;
    result.imag = c1.real * c2.imag + c1.imag * c2.real;
    return result;
}

void printComplex(Complex c) {
    printf("%.2f + %.2fi\n", c.real, c.imag);
}

int main() {
    Complex c1 = {3.0, 4.0};
    Complex c2 = {1.0, 2.0};

    Complex sum = add(c1, c2);
    Complex difference = subtract(c1, c2);
    Complex product = multiply(c1, c2);

    printf("Sum: ");
    printComplex(sum);
    printf("Difference: ");
    printComplex(difference);
    printf("Product: ");
    printComplex(product);

    return 0;
}

在上面的代码中,定义了一个Complex结构体来表示复数,然后定义了三个函数来实现复数的加法、减法和乘法运算。在main函数中,创建了两个复数c1c2,并调用相应的函数来进行运算,并输出结果。

0
看了该问题的人还看了