建立一个复数类Complex,其私有数据成员mX和mY表示复数的实部和虚部,构造函数Complex用于对复数的实部和虚部初始化

建立一个复数类Complex,其私有数据成员mX和mY表示复数的实部和虚部,构造函数Complex用于对复数的实部和虚部初始化,友员函数Add,Sub,Mul和Div分别用于进行复数的加、减、乘和除法运算,函数Show用于显示运算结果。在主函数中,实例化两个复数,并输入一个运算符,按运算符选择相应的友员函数进行复数运算,然后输出运算结果。


//Complex .h

#pragma once
class Complex
{
public:

	Complex(double a=0,double b=0);
	friend Complex add(Complex a, Complex b);
	friend Complex sub(Complex a, Complex b);
	friend Complex mul(Complex a, Complex b);
	friend Complex div(Complex a, Complex b);
	void show();
private:
	double mx, my;

};
//complex cpp
#include "pch.h"
#include "Complex.h"
#include 
#include
using namespace std;

Complex::Complex(double a, double b)
{
	mx = a;
	my = b;
}
Complex add(Complex a, Complex b)
{
	double cx = a.mx + b.mx;
	double cy = a.my + b.my;
	Complex p = Complex(cx, cy);
	return p;
}
Complex sub(Complex a, Complex b)
{
	double cx = a.mx - b.mx;
	double cy = a.my - b.my;
	Complex p = Complex(cx, cy);
	return p;
}
Complex mul(Complex a, Complex b)
{
	double cx = a.mx * b.mx - a.my * b.my;
	double cy = a.my * b.mx + a.mx * b.my;
	Complex p = Complex(cx, cy);
	return p;
}
Complex div(Complex a, Complex b)
{
	double cx = (a.mx * b.mx + a.my*b.my) / (pow(b.mx, 2) + pow(b.my, 2));
	double cy = (a.my * b.mx - a.mx*b.my)/(pow(b.mx, 2) + pow(b.my, 2));
	Complex p = Complex(cx, cy);
	return p;
}
void Complex::show()
{
	if(mx==0) cout << "answer:" << my << 'i' << endl;
	else if(my>0) cout << "answer:" << mx << '+' << my << 'i' << endl;
	else if(my<0) cout << "answer:" << mx << my << 'i' << endl;
	else cout << "answer:" << mx << endl;
}
//main cpp

#include "pch.h"
#include "Complex.h"
#include 
using namespace std;
int main()
{
	char a;
	double b, c, d, e;
	while (cin >> a >> b >> c >> d >> e)
	{
		Complex x(b, c), y(d, e);
		Complex p;
		switch (a)
		{
		case '+':p = add(x, y); break;
		case '-':p = sub(x, y); break;
		case '*':p = mul(x, y); break;
		default:p = div(x, y); break;
			break;
		}
		p.show();
	}
}

你可能感兴趣的:(建立一个复数类Complex,其私有数据成员mX和mY表示复数的实部和虚部,构造函数Complex用于对复数的实部和虚部初始化)