在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
函數中,創建了兩個復數c1
和c2
,并調用相應的函數來進行運算,并輸出結果。