c语言编写程序,用结构体类型实现复数的加、减、乘、除运算,每种运算用函数完成。
时间: 2023-05-21 07:00:40 浏览: 368
可以使用以下代码实现:
```c
#include <stdio.h>
typedef struct {
double real;
double imag;
} Complex;
Complex add(Complex a, Complex b) {
Complex result;
result.real = a.real + b.real;
result.imag = a.imag + b.imag;
return result;
}
Complex sub(Complex a, Complex b) {
Complex result;
result.real = a.real - b.real;
result.imag = a.imag - b.imag;
return result;
}
Complex mul(Complex a, Complex b) {
Complex result;
result.real = a.real * b.real - a.imag * b.imag;
result.imag = a.real * b.imag + a.imag * b.real;
return result;
}
Complex div(Complex a, Complex b) {
Complex result;
double denominator = b.real * b.real + b.imag * b.imag;
result.real = (a.real * b.real + a.imag * b.imag) / denominator;
result.imag = (a.imag * b.real - a.real * b.imag) / denominator;
return result;
}
int main() {
Complex a = {1.0, 2.0};
Complex b = {3.0, 4.0};
Complex c = add(a, b);
printf("a + b = %.2f + %.2fi\n", c.real, c.imag);
c = sub(a, b);
printf("a - b = %.2f + %.2fi\n", c.real, c.imag);
c = mul(a, b);
printf("a * b = %.2f + %.2fi\n", c.real, c.imag);
c = div(a, b);
printf("a / b = %.2f + %.2fi\n", c.real, c.imag);
return 0;
}
```
这个程序定义了一个复数结构体,然后实现了加、减、乘、除四种运算的函数。在主函数中,我们定义了两个复数,然后分别调用这四个函数,输出结果。
阅读全文