在C語言中,可以通過定義一個結構體來表示復數,然后再定義一個函數來實現兩個復數的相加操作。以下是一個示例代碼:
#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;
}
運行程序后,用戶將被提示分別輸入兩個復數的實部和虛部,然后程序將計算并輸出它們的和。