用c语言模块化编写复数实现的代码
时间: 2023-05-20 12:06:32 浏览: 98
非常感谢您的提问!以下是一个用 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;
}
// 复数模长
double abs(Complex a) {
return sqrt(a.real * a.real + a.imag * a.imag);
}
// 复数共轭
Complex conj(Complex a) {
Complex c;
c.real = a.real;
c.imag = -a.imag;
return c;
}
// 复数实部
double real(Complex a) {
return a.real;
}
// 复数虚部
double imag(Complex a) {
return a.imag;
}
// 复数输出
void print(Complex a) {
printf("%.2f + %.2fi\n", a.real, a.imag);
}
希望这个代码示例能够帮助您解决问题!
阅读全文