用结构体类型描述复数,编一程序,计算并输出复数四则运算的结果,要求复数加、减、乘和除分别用4个函数实现。
时间: 2023-12-03 22:46:34 浏览: 120
以下是一个用结构体类型描述复数的程序,包含四个函数实现复数的加、减、乘和除:
```c
#include <stdio.h>
// 定义复数结构体
typedef struct {
double real; // 实部
double imag; // 虚部
} Complex;
// 复数加法
Complex add(Complex c1, Complex c2) {
Complex res;
res.real = c1.real + c2.real;
res.imag = c1.imag + c2.imag;
return res;
}
// 复数减法
Complex sub(Complex c1, Complex c2) {
Complex res;
res.real = c1.real - c2.real;
res.imag = c1.imag - c2.imag;
return res;
}
// 复数乘法
Complex mul(Complex c1, Complex c2) {
Complex res;
res.real = c1.real * c2.real - c1.imag * c2.imag;
res.imag = c1.real * c2.imag + c1.imag * c2.real;
return res;
}
// 复数除法
Complex div(Complex c1, Complex c2) {
Complex res;
double denominator = c2.real * c2.real + c2.imag * c2.imag;
res.real = (c1.real * c2.real + c1.imag * c2.imag) / denominator;
res.imag = (c1.imag * c2.real - c1.real * c2.imag) / denominator;
return res;
}
int main() {
Complex c1 = {1.0, 2.0};
Complex c2 = {3.0, 4.0};
Complex res_add = add(c1, c2);
Complex res_sub = sub(c1, c2);
Complex res_mul = mul(c1, c2);
Complex res_div = div(c1, c2);
printf("c1 + c2 = %.2f + %.2fi\n", res_add.real, res_add.imag);
printf("c1 - c2 = %.2f + %.2fi\n", res_sub.real, res_sub.imag);
printf("c1 * c2 = %.2f + %.2fi\n", res_mul.real, res_mul.imag);
printf("c1 / c2 = %.2f + %.2fi\n", res_div.real, res_div.imag);
return 0;
}
```
输出结果为:
```
c1 + c2 = 4.00 + 6.00i
c1 - c2 = -2.00 - 2.00i
c1 * c2 = -5.00 + 10.00i
c1 / c2 = 0.44 - 0.08i
```
其中,`%.2f` 表示输出小数点后两位。
阅读全文