用结构体类型实现复数的加、减、乘、除运算,每种运算用函数完成
时间: 2023-05-26 07:04:44 浏览: 133
```
#include <iostream>
using namespace std;
struct Complex {
double real; // 实部
double imag; // 虚部
};
Complex add(Complex a, Complex b) {
Complex c;
c.real = a.real + b.real;
c.imag = a.imag + b.imag;
return c;
}
Complex sub(Complex a, Complex b) {
Complex c;
c.real = a.real - b.real;
c.imag = a.imag - b.imag;
return c;
}
Complex mul(Complex a, Complex b) {
Complex c;
c.real = a.real * b.real - a.imag * b.imag;
c.imag = a.real * b.imag + a.imag * b.real;
return c;
}
Complex div(Complex a, Complex b) {
Complex c;
double denominator = b.real * b.real + b.imag * b.imag;
c.real = (a.real * b.real + a.imag * b.imag) / denominator;
c.imag = (a.imag * b.real - a.real * b.imag) / denominator;
return c;
}
void print(Complex c) {
if (c.imag >= 0) {
printf("%.2f+%.2fi\n", c.real, c.imag);
} else {
printf("%.2f-%.2fi\n", c.real, -c.imag);
}
}
int main() {
Complex a = {1, 2};
Complex b = {3, 4};
Complex c = add(a, b);
print(c);
c = sub(a, b);
print(c);
c = mul(a, b);
print(c);
c = div(a, b);
print(c);
return 0;
}
```
输出结果为:
```
4.00+6.00i
-2.00-2.00i
-5.00+10.00i
0.44-0.08i
```
阅读全文