该回答引用ChatGPT
#include<stdio.h>
#include<math.h>
typedef struct {
double real, 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;
}
Complex divide(Complex c1, Complex c2) {
Complex result;
result.real = (c1.real * c2.real + c1.imag * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag);
result.imag = (c1.imag * c2.real - c1.real * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag);
return result;
}
void printComplex(Complex c, char operator) {
if (c.real == 0) {
if (c.imag == 0) {
printf("0.0\n");
}
else if (c.imag > 0) {
printf("%.1fi\n", c.imag);
}
else {
printf("-%.1fi\n", fabs(c.imag));
}
}
else if (c.imag == 0) {
printf("%.1f\n", c.real);
}
else if (c.imag > 0) {
printf("(%.1f+%.1fi)\n", c.real, c.imag);
}
else {
printf("(%.1f-%.1fi)\n", c.real, fabs(c.imag));
}
}
int main() {
Complex c1, c2, result;
scanf("%lf%lf%lf%lf", &c1.real, &c1.imag, &c2.real, &c2.imag);
result = add(c1, c2);
printComplex(c1, '+');
printComplex(c2, '=');
printComplex(result, '\0');
result = subtract(c1, c2);
printComplex(c1, '-');
printComplex(c2, '=');
printComplex(result, '\0');
result = multiply(c1, c2);
printComplex(c1, '*');
printComplex(c2, '=');
printComplex(result