complexnum.cpp

来自「This file implements the ComplexNum clas」· C++ 代码 · 共 98 行

CPP
98
字号
//****************************************************************
// Implementation file (ComplexNum.cpp)
// This file implements the ComplexNum class member functions. 
// Programming Problems No.3 on P472 of textbook. 
//****************************************************************
#include "complexNum.h"
#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

// Private members of class
//     double  real, imag;
//*****************************************************************

ComplexNum::ComplexNum(/*in*/double r,/*in*/double i)
{
	real = r;
	imag = i;
}

//*****************************************************************
ComplexNum::ComplexNum()
{
	real = 0.0;
	imag = 0.0;
}

//*****************************************************************
void ComplexNum::Set(/*in*/double r, //real part of the complex number
		             /*in*/double i)//imaginary part of the complex number
{
	real = r;
	imag = i;
}

//*****************************************************************
ComplexNum ComplexNum::Cadd(/*in*/ComplexNum other) const	
{
	ComplexNum result;
	result.real = real + other.real;
	result.imag = imag + other.imag;
	return result;
}

//*****************************************************************
ComplexNum ComplexNum::Csub(/*in*/ComplexNum other) const
{
	ComplexNum result;
	result.real = real - other.real;
	result.imag = imag - other.imag;
	return result;
}

//*****************************************************************
ComplexNum ComplexNum::Cmult(/*in*/ComplexNum other) const
{
	ComplexNum result;
	result.real = real*other.real - imag*other.imag;
	result.imag = real*other.imag + imag*other.real;
	return result;
}

//*****************************************************************
ComplexNum ComplexNum::Cdiv(/*in*/ComplexNum other) const
{
	ComplexNum result;
	result.real = ( real * other.real + imag * other.imag )
		          / ( pow( other.real, 2 ) + pow( other.imag, 2 ) );
	result.imag = ( imag * other.real + real * other.imag )
				  / ( pow( other.real, 2 ) + pow( other.imag, 2 ) );
	return result;
}

//*****************************************************************
double ComplexNum::Cabs() const
{
	return sqrt( real * real + imag * imag );
}

//*****************************************************************
void ComplexNum::Print() const
{
	cout<< "(" << real << ", " << imag << ")" << endl;
}

//*****************************************************************
double ComplexNum::RealPart()const
{
  return real;
}

//*****************************************************************
double ComplexNum::ImagPart()const
{
  return imag;
}

⌨️ 快捷键说明

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