用c++写出复数的计算
时间: 2023-03-28 08:00:38 浏览: 104
C++编写的复数计算器
3星 · 编辑精心推荐
可以使用结构体来表示复数,例如:
```c
typedef struct {
double real; // 实部
double imag; // 虚部
} complex;
// 复数加法
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 d = b.real * b.real + b.imag * b.imag;
c.real = (a.real * b.real + a.imag * b.imag) / d;
c.imag = (a.imag * b.real - a.real * b.imag) / d;
return c;
}
```
使用时,可以先定义两个复数:
```c
complex a = {1., 2.}; // 1+2i
complex b = {3., 4.}; // 3+4i
```
然后进行计算:
```c
complex c = add(a, b); // c = a + b = 4+6i
complex d = sub(a, b); // d = a - b = -2-2i
complex e = mul(a, b); // e = a * b = -5+10i
complex f = div(a, b); // f = a / b = .44+.08i
```
阅读全文