使用C語(yǔ)言處理復(fù)數(shù)有什么技巧

小樊
87
2024-07-17 22:50:53

處理復(fù)數(shù)時(shí),可以使用結(jié)構(gòu)體來(lái)表示復(fù)數(shù)的實(shí)部和虛部,然后定義相應(yīng)的操作函數(shù)來(lái)實(shí)現(xiàn)復(fù)數(shù)的加減乘除等運(yùn)算。下面是一個(gè)簡(jiǎn)單的示例代碼:

#include <stdio.h>

typedef struct {
    double real;
    double 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;
}

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

void printComplex(Complex c) {
    if (c.imaginary >= 0) {
        printf("%.2f + %.2fi\n", c.real, c.imaginary);
    } else {
        printf("%.2f - %.2fi\n", c.real, -c.imaginary);
    }
}

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;
}

這段代碼定義了一個(gè)Complex結(jié)構(gòu)體,包含了實(shí)部和虛部,然后定義了加法、減法、乘法等操作函數(shù),并在main函數(shù)中測(cè)試了這些操作。通過(guò)結(jié)構(gòu)體和函數(shù)的封裝,可以方便地處理復(fù)數(shù)的運(yùn)算。

0