complex.cpp

来自「复数类」· C++ 代码 · 共 113 行

CPP
113
字号
#include "complex.h"
#include <math.h>
#include <stdio.h>

complex::complex(){
	real = 0 ;
	imag = 0 ;
}

complex::complex(double r , double i){
	real = r ;
	imag = i ;
}

complex::complex(complex& c){
	real = c.real ;
	imag = c.imag ;
}

complex::complex(double r){
	real = r ;
	imag = 0 ;
}

complex::~complex(){
	
}

complex& complex::operator= ( complex &c){
	real = c.real ;
	imag = c.imag ;
	return *this;
}

complex& complex::add(complex& c){
	real += c.real ;
	imag += c.imag ;
	return *this ;
}

complex& complex::sub(complex& c){
	real -= c.real ;
	imag -= c.imag ;
	return *this ;
}

complex& complex::mul(complex& c){
	complex tmp ;
	tmp.real = real * c.real - imag * c.imag ;
	tmp.imag = real * c.imag + imag * c.real ;
	*this = tmp ;
	return *this ;
}

complex& complex::div(complex& c){
	double mo = real * c.real + imag * c.imag ;
	real = ( real * c.real + imag * c.imag ) / mo ;
	imag = ( -real * c.imag + imag * c.real ) / mo ;
	return *this ;
}

complex& complex::operator+= (complex &c){
	return add(c);
}

complex& complex::operator-= (complex &c){
	return sub(c);
}

complex& complex::operator*= (complex &c){
	return mul(c);
}

complex& complex::operator/= (complex &c){
	return div(c);
}

complex complex::operator+ ( complex &c ){
	complex tmp ;
	tmp = *this ;
	tmp.add(c);
	return tmp ;
}

complex complex::operator- ( complex &c ){
	complex tmp ;
	tmp = *this ;
	tmp.sub(c);
	return tmp ;
}

complex complex::operator* ( complex &c ){
	complex tmp ;
	tmp = *this ;
	tmp.mul(c);
	return tmp ;
}

complex complex::operator/ ( complex &c ){
	complex tmp ;
	tmp = *this ;
	tmp.div(c);
	return tmp ;
}

void complex::output(){
	printf("%*.*f",_COMPLEX_OUTPUT_WIDTH,_COMPLEX_OUTPUT_DECIMAL,real);
	if ( fabs(imag) > _COMPLEX_EPS ){
		if ( imag > 0 ) putchar('+') ;
		printf("%*.*fi",_COMPLEX_OUTPUT_WIDTH,_COMPLEX_OUTPUT_DECIMAL,imag);
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?