C++ 实现复数 ADT 及其应用示例
#include
struct Complex { double real; // 实部 double imag; // 虚部 };
void Create(double x, double y, Complex& z) { z.real = x; z.imag = y; }
void Add(const Complex& z1, const Complex& z2, Complex& sum) { sum.real = z1.real + z2.real; sum.imag = z1.imag + z2.imag; }
void Subtract(const Complex& z1, const Complex& z2, Complex& difference) { difference.real = z1.real - z2.real; difference.imag = z1.imag - z2.imag; }
void Multiply(const Complex& z1, const 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(const Complex& z, double& e) { e = z.real; }
void Get_ImagPart(const Complex& z, double& e) { e = z.imag; }
int main() { Complex z1, z2, sum, difference, product; double realPart, imagPart;
Create(2.0, 3.0, z1);
Create(1.0, -2.0, z2);
Add(z1, z2, sum);
Subtract(z1, z2, difference);
Multiply(z1, z2, product);
Get_RealPart(sum, realPart);
Get_ImagPart(sum, imagPart);
cout << 'Sum: ' << realPart << ' + ' << imagPart << 'i' << endl;
Get_RealPart(difference, realPart);
Get_ImagPart(difference, imagPart);
cout << 'Difference: ' << realPart << ' + ' << imagPart << 'i' << endl;
Get_RealPart(product, realPart);
Get_ImagPart(product, imagPart);
cout << 'Product: ' << realPart << ' + ' << imagPart << 'i' << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/m1I5 著作权归作者所有。请勿转载和采集!