如何用c语言写复数的基本运算
时间: 2023-03-30 20:04:43 浏览: 144
复数的基本运算可以通过定义结构体来实现,结构体中包含实部和虚部两个成员变量,具体代码如下:
```
#include <stdio.h>
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;
}
int main() {
Complex a = {1., 2.};
Complex b = {3., 4.};
Complex c;
c = add(a, b);
printf("(%g + %gi) + (%g + %gi) = %g + %gi\n", a.real, a.imag, b.real, b.imag, c.real, c.imag);
c = sub(a, b);
printf("(%g + %gi) - (%g + %gi) = %g + %gi\n", a.real, a.imag, b.real, b.imag, c.real, c.imag);
c = mul(a, b);
printf("(%g + %gi) * (%g + %gi) = %g + %gi\n", a.real, a.imag, b.real, b.imag, c.real, c.imag);
c = div(a, b);
printf("(%g + %gi) / (%g + %gi) = %g + %gi\n", a.real, a.imag, b.real, b.imag, c.real, c.imag);
return ;
}
```
阅读全文