用C语言定义一个纯虚数,实部和虚部分开储存和计算的函数并可执行
时间: 2024-03-01 21:55:05 浏览: 231
用C++实现虚函数
5星 · 资源好评率100%
可以使用结构体来定义一个纯虚数,结构体中包含实数部分和虚数部分的变量。下面是一个例子:
```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 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.0, 2.0};
Complex b = {3.0, 4.0};
Complex c = add(a, b);
printf("add: %lf + %lfi\n", c.real, c.imag);
c = sub(a, b);
printf("sub: %lf + %lfi\n", c.real, c.imag);
c = mul(a, b);
printf("mul: %lf + %lfi\n", c.real, c.imag);
c = div(a, b);
printf("div: %lf + %lfi\n", c.real, c.imag);
return 0;
}
```
这里定义了四个基本的运算函数,分别实现两个复数的加减乘除。在主函数中,定义了两个复数 a 和 b,并且调用了这四个运算函数,将结果打印出来。输出结果如下:
```
add: 4.000000 + 6.000000i
sub: -2.000000 + -2.000000i
mul: -5.000000 + 10.000000i
div: 0.440000 + -0.080000i
```
可以看到,程序成功地实现了纯虚数的计算。
阅读全文