在C語(yǔ)言中,可以通過(guò)定義一個(gè)結(jié)構(gòu)體來(lái)表示復(fù)數(shù),然后再定義一個(gè)函數(shù)來(lái)實(shí)現(xiàn)兩個(gè)復(fù)數(shù)的相加操作。以下是一個(gè)示例代碼:
#include <stdio.h>
typedef struct complex {
float real;
float imag;
} Complex;
Complex add(Complex c1, Complex c2) {
Complex result;
result.real = c1.real + c2.real;
result.imag = c1.imag + c2.imag;
return result;
}
int main() {
Complex c1, c2, sum;
printf("Enter real and imaginary parts of first complex number: ");
scanf("%f %f", &c1.real, &c1.imag);
printf("Enter real and imaginary parts of second complex number: ");
scanf("%f %f", &c2.real, &c2.imag);
sum = add(c1, c2);
printf("Sum = %.2f + %.2fi\n", sum.real, sum.imag);
return 0;
}
運(yùn)行程序后,用戶將被提示分別輸入兩個(gè)復(fù)數(shù)的實(shí)部和虛部,然后程序?qū)⒂?jì)算并輸出它們的和。