用c语言写复数实现的代码
时间: 2023-05-20 10:06:28 浏览: 84
以下是用 C 语言实现复数的代码:
```c
#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 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;
}
void print_complex(Complex c) {
printf("%.2f + %.2fi\n", c.real, c.imag);
}
int main() {
Complex a = {1.0, 2.0};
Complex b = {3.0, 4.0};
Complex c = add(a, b);
Complex d = sub(a, b);
Complex e = mul(a, b);
Complex f = div(a, b);
print_complex(c);
print_complex(d);
print_complex(e);
print_complex(f);
return 0;
}
```
这个程序定义了一个复数类型 `Complex`,并实现了加、减、乘、除四种基本运算。在 `main` 函数中,我们定义了两个复数 `a` 和 `b`,并对它们进行了加、减、乘、除运算,最后将结果输出。
阅读全文