浙大版《c语言程序设计(第3版)》复数四则运算
时间: 2023-09-19 20:05:02 浏览: 107
用C语言实现复数的四则运算
以下是浙大版《c语言程序设计(第3版)》中复数四则运算的示例代码:
```c
#include <stdio.h>
typedef struct {
double real, 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 r2 = b.real * b.real + b.imag * b.imag;
c.real = (a.real * b.real + a.imag * b.imag) / r2;
c.imag = (a.imag * b.real - a.real * b.imag) / r2;
return c;
}
int main() {
complex a = {1, 2}, b = {3, 4};
complex 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 0;
}
```
输出结果为:
```
(1+2i)+(3+4i)=4+6i
(1+2i)-(3+4i)=-2-2i
(1+2i)*(3+4i)=-5+10i
(1+2i)/(3+4i)=0.44+0.08i
```
该示例代码定义了一个 `complex` 结构体类型,包含实部和虚部两个成员变量。四个函数分别实现了复数的加、减、乘、除操作。在 `main` 函数中,分别定义了两个复数 `a` 和 `b`,并使用四个函数进行运算,最后输出结果。
阅读全文