现在的位置: 首页 > 综合 > 正文

复数的加减乘除及开方乘方运算

2018年01月30日 ⁄ 综合 ⁄ 共 2480字 ⁄ 字号 评论关闭
#include<iostream>
#include<math.h>
using namespace std;

const double pi=3.1415926535897932384626433;

class Fushu{
private:
	double x, y;
public:
	Fushu(){x=0.0;y=0.0;}
	Fushu operator +(const Fushu& f);
	Fushu operator -(const Fushu& f);
	Fushu operator *(const Fushu& f);
	Fushu operator /(const Fushu& f);
	void operator =(const Fushu& f);
	void cf(int n);
	void kf(int n);
	friend ostream& operator <<(ostream& Os, const Fushu& f);
	friend istream& operator >>(istream& In,  Fushu& f);
};


//////////////////   operator +   /////////////////////////////

Fushu Fushu::operator +(const Fushu& f){
	Fushu tem;
	tem.x=(*this).x+f.x;
	tem.y=(*this).y+f.y;
	return tem;
}


//////////////////   operator -   /////////////////////////////

Fushu Fushu::operator -(const Fushu& f){
	Fushu tem;
	tem.x=(*this).x-f.x;
	tem.y=(*this).y-f.y;
	return tem;
}


//////////////////   operator *   /////////////////////////////

Fushu Fushu::operator *(const Fushu& f){
	Fushu tem;
	tem.x=(*this).x*f.x-(*this).y*f.y;    
	tem.y=(*this).y*f.x+(*this).x*f.y;    
	return tem;
}


//////////////////   operator /   /////////////////////////////

Fushu Fushu::operator /(const Fushu& f){
	Fushu tem;
	tem.x=((*this).x*f.x+(*this).y*f.y)/((*this).y*(*this).y+f.y*f.y);
	tem.y=((*this).y*f.x-(*this).x*f.y)/((*this).y*(*this).y+f.y*f.y);
	return tem;
}


//////////////////   operator =   /////////////////////////////

void Fushu::operator =(const Fushu& f){
	// Fushu tem;
	(*this).x=f.x;
	(*this).y=f.y;
	// return tem;
}

//////////////////   乘方   /////////////////////////////
void Fushu::cf(int n){
	Fushu tem;
	//if(n<0) cout<<""
	if(n==0){
		tem.x=1;
		tem.y=0;
	}
	else if (n==1){
		tem.x=(*this).x;
		tem.y=(*this).y;
	}
	else 
	{
		double r,j;
		r=sqrt((*this).x*(*this).x+(*this).y*(*this).y);
		j=atan((*this).y/(*this).x);
		tem.x=pow(r,n)*cos(n*j);
		tem.y=pow(r,n)*sin(n*j);

	}
	cout<<(*this)<<"乘"<<n<<"次方为:/n "<<tem<<endl;

}


//////////////////   开方   /////////////////////////////
void Fushu::kf(int n){
	Fushu tem;
	double r,j;
	r=sqrt((*this).x*(*this).x+(*this).y*(*this).y);
	j=atan((*this).y/(*this).x);
	cout<<(*this)<<"的开"<<n<<"次方为:"<<endl;
	for(int i=0;i<n;i++){
		tem.x=pow(r,1.0/n)*cos((j+i*pi*2.0)/n);
		tem.y=pow(r,1.0/n)*sin((j+i*pi*2.0)/n);
		cout<<tem<<endl;
	}
	return;
}


//////////////////   输出重载   /////////////////////////////

ostream& operator <<(ostream &os, const Fushu &f){
	if(f.y<0)
		return os<<f.x<<f.y<<"i";
	else
		return os<<f.x<<"+"<<f.y<<"i";
}


//////////////////   输入重载   /////////////////////////////

istream& operator >>(istream & in,  Fushu & f){
	in>>f.x>>f.y;
	return in;
}

void main(){
	Fushu a,b,c;

	cout<<"请输入复数a和b/n";
	cin>>a;
	cin>>b;
	cout<<"a="<<a<<endl;
	cout<<"b="<<b<<endl;
	c=a+b;
	cout<<"c=a+b="<<a+b<<endl;
	c=a-b;
	cout<<"c=a-b="<<a-b<<endl;
	c=a*b;
	cout<<"c=a*b="<<b*a<<endl;
	c=a/b;
	cout<<"c=a/b="<<a/b<<endl;

	c.cf(2);
	c.kf(2);

}

 

抱歉!评论已关闭.