C++程序设计小实验②(类与对象)

题目:
建立一个复数类imaginary,其私有数据成员x和y表示复数的实部和虚部,构造函数imaginary用于对复数的实部和虚部初始化,友员函数add,sub,mul和div分别用于进行复数的加、减、乘和除法运算,静态函数show用于显示运算结果。在主函数中,实例化两个复数,并输入一个运算符,按运算符选择相应的友员函数进行复数运算,然后输出运算结果。

假设有两个复数a+bi和c+di,则复数的加、减、乘和除法运算规定如下
(a+bi)+(c-K/i)=(a+c)+(b+d)i
(a+bi)-(c+di)=(a-c)+(b-d)i
(a+bi)*(c+di)=(ac-bd)+(bc+ad)i
(a+bi)/(c+di)=(ac+bd)/(c2+d2)+(bc-ad)/ (c2+d2)i

#include 

using namespace std;

class  imaginary
{
	double x, y;
	
public:
	static double A, B;//用于储存计算结果的静态成员变量

	imaginary(double a, double b);//构造函数
	friend void add(imaginary& obj, imaginary& obj1 );
	friend void sub(imaginary& obj, imaginary& obj1);
	friend void mul(imaginary& obj, imaginary& obj1);
	friend void div(imaginary& obj, imaginary& obj1);

	static void show();

};

//需要在类外定义静态数据成员
double imaginary::A = 0;
double imaginary::B = 0;

imaginary::imaginary(double a, double b):x(a),y(b){}  //构造函数实现

void show()
{
	cout << imaginary::A << "i" <<"+"<<"("<< imaginary::B <<")"<< "j" << endl;
}
void  add(imaginary& obj, imaginary& obj1)
{
	imaginary::A= obj.x + obj1.x;
	imaginary::B= obj.y + obj1.y;

}
void sub(imaginary& obj, imaginary& obj1)
{
	imaginary::A = obj.x - obj1.x;
	imaginary::B = obj.y - obj1.y;
}
void mul(imaginary& obj, imaginary& obj1)
{
	imaginary::A = ((obj.x * obj1.x) - (obj.y * obj1.y));
	imaginary::B = ((obj.y * obj1.x) + (obj.x * obj1.y));
}
void div(imaginary& obj, imaginary& obj1)
{
	imaginary::A = (obj.x * obj1.x + obj.y * obj1.y) / (obj1.x * obj1.x + obj1.y * obj1.y);
	imaginary::B = (obj.y * obj1.x - obj.x * obj1.y) / (obj1.x * obj1.x + obj1.y * obj1.y);

}


int main()
{
	double p, o, i, u;

	cout << "请输入第一个复数的实部:  ";
	cin >> p;
	cout << "请输入第一个复数的虚部:  ";
	cin >> o;
	cout << endl;

	cout << "请输入第二个复数的实部:  ";
	cin >> i;
	cout << "请输入第二个复数的虚部:  ";
	cin >> u;
	

	imaginary obj(p, o);
	imaginary obj1(i, u);

	char x;
	cout << "请输入一个运算符,运算两个复数" << endl;
    cin >> x;

	switch (x)
	{
	case '+' :
	{
		add(obj, obj1);
		show();
	} break;
	case '-':
	{
		sub(obj, obj1);
		show();
	}break;
	case'*':
	{
		mul(obj, obj1);
		show();
	}break;
	case'/':
	{
		div(obj, obj1);
		show();
	}break;





	}

}


你可能感兴趣的:(C++程序设计小实验②(类与对象))