C语言实现复数抽象数据类型及应用示例
#include <stdio.h> #include <stdlib.h>
typedef struct { float real; float imag; } Complex;
void Create(float x, float y, Complex* z) { z->real = x; z->imag = y; }
void Add(Complex z1, Complex z2, Complex* sum) { sum->real = z1.real + z2.real; sum->imag = z1.imag + z2.imag; }
void Subtract(Complex z1, Complex z2, Complex* difference) { difference->real = z1.real - z2.real; difference->imag = z1.imag - z2.imag; }
void Multiply(Complex z1, Complex z2, Complex* product) { product->real = z1.real * z2.real - z1.imag * z2.imag; product->imag = z1.real * z2.imag + z2.real * z1.imag; }
void Get_RealPart(Complex z, float* e) { *e = z.real; }
void Get_ImagPart(Complex z, float* e) { *e = z.imag; }
int main() { Complex z1, z2, sum, difference, product; float realPart, imagPart;
Create(2, 3, &z1);
Create(4, 5, &z2);
Add(z1, z2, &sum);
Subtract(z1, z2, &difference);
Multiply(z1, z2, &product);
Get_RealPart(sum, &realPart);
Get_ImagPart(sum, &imagPart);
printf('Sum: %.2f + %.2fi\n', realPart, imagPart);
Get_RealPart(difference, &realPart);
Get_ImagPart(difference, &imagPart);
printf('Difference: %.2f + %.2fi\n', realPart, imagPart);
Get_RealPart(product, &realPart);
Get_ImagPart(product, &imagPart);
printf('Product: %.2f + %.2fi\n', realPart, imagPart);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/m1Lx 著作权归作者所有。请勿转载和采集!