在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;
}
运行程序后,用户将被提示分别输入两个复数的实部和虚部,然后程序将计算并输出它们的和。