用结构体实现复数的加减乘除
时间: 2023-04-02 17:01:47 浏览: 138
复数运算问题 简单的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 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;
}
这样就可以通过调用 add、sub、mul、div 函数来实现复数的加减乘除了。
阅读全文