要使用C語言實現復數的加減乘除,可以先定義一個結構體表示復數,然后編寫相應的函數來進行運算。
以下是一個示例:
#include <stdio.h>
// 定義復數結構體
typedef struct {
double real; // 實部
double imaginary; // 虛部
} Complex;
// 復數加法
Complex add(Complex a, Complex b) {
Complex result;
result.real = a.real + b.real;
result.imaginary = a.imaginary + b.imaginary;
return result;
}
// 復數減法
Complex subtract(Complex a, Complex b) {
Complex result;
result.real = a.real - b.real;
result.imaginary = a.imaginary - b.imaginary;
return result;
}
// 復數乘法
Complex multiply(Complex a, Complex b) {
Complex result;
result.real = a.real * b.real - a.imaginary * b.imaginary;
result.imaginary = a.real * b.imaginary + a.imaginary * b.real;
return result;
}
// 復數除法
Complex divide(Complex a, Complex b) {
Complex result;
double denominator = b.real * b.real + b.imaginary * b.imaginary;
result.real = (a.real * b.real + a.imaginary * b.imaginary) / denominator;
result.imaginary = (a.imaginary * b.real - a.real * b.imaginary) / denominator;
return result;
}
// 測試函數
int main() {
Complex a = {1.0, 2.0};
Complex b = {3.0, 4.0};
Complex sum = add(a, b);
printf("Sum: %lf + %lfi\n", sum.real, sum.imaginary);
Complex difference = subtract(a, b);
printf("Difference: %lf + %lfi\n", difference.real, difference.imaginary);
Complex product = multiply(a, b);
printf("Product: %lf + %lfi\n", product.real, product.imaginary);
Complex quotient = divide(a, b);
printf("Quotient: %lf + %lfi\n", quotient.real, quotient.imaginary);
return 0;
}
這個示例中,我們使用了一個結構體來表示復數,包含了實部和虛部。然后,我們編寫了四個函數來分別實現復數的加法、減法、乘法和除法。在主函數中,我們定義了兩個復數a和b,并通過這四個函數進行了加減乘除運算,并打印了結果。
注意,這只是一個簡單的示例,實際情況中可能需要更多的錯誤處理和邊界情況的考慮。