c++学习日记之复数的运算

复数有两个部分:实数部分和虚数部分。假设 a=(A,Bi),c=(C,Di);则
加法:a+c = (A+C,(B+D)i)
减法:a-c = (A-C,(B-D)i)
乘法:a*c = (A*C-B*D,(A*D+B*C)i)
实属乘法:x*c=(x*C,(x*D)i)
共轭:~a=(A,Bi)
我们通过定义复数类,并对 + - * ~ >> <<等运算符进行重载,分别利用成员函数与非成员函数重载的方法。
代码如下:
complex.h文件
#ifndef COMPLEX_H_
#define COMPLEX_H_
#include<iostream>
class complex
{
public:
	double real;
	double imaginary;
public:
	complex():real(0.0),imaginary(0.0) {}
	complex(double r,double imag):real(r),imaginary(imag) {}
	~complex()
	{

	}
	complex operator + (const complex &c);
	complex operator - (const complex &c);
	complex operator * (const complex &c);
    complex operator ~ ();
	friend complex operator *(double n,complex &c);
	friend std::istream & operator >> (std::istream &os,complex &c);
	friend std::ostream & operator << (std::ostream &os,const complex &c);

};
#endif


complex.cpp文件 即复数类的实现
#include"complex.h"
#include<string>
complex complex::operator+(const complex &c)
{
	complex temp;
	temp.real=this->real+c.real;
	temp.imaginary=this->imaginary+c.imaginary;
	return temp;
}
complex complex::operator*(const complex &c)
{
	complex temp;
	temp.real=this->real*c.real-this->imaginary*c.imaginary;
	temp.imaginary=this->real*c.imaginary+this->imaginary*c.real;
	return temp;
}
complex complex::operator-(const complex &c)
{
	complex temp;
	temp.real=this->real-c.real;
	temp.imaginary=this->imaginary-c.imaginary;
	return temp;
}
complex complex::operator~()
{
	complex temp;
	temp.real=this->real;
	temp.imaginary=-this->imaginary;
	return temp;
}

std::istream &operator >> (std::istream &os,complex &c)
{
	std::cout << "real: ";
	if (!(os >> c.real))
		return os;
	std::cout << "imaginary: ";
	if(!(os >> c.imaginary))
		return os;
	return os;
}
std::ostream &operator << (std::ostream & os,const complex &c)
{
	os <<"("<<c.real<< ", " << c.imaginary << "i)";
	return os;
}
complex operator * (double n,complex &c)
{
	complex temp;
	temp.real=n*c.real;
	temp.imaginary=n*c.imaginary;
	return temp;
}


main()函数
using namespace std;
#include "complex.h"
int main()
{
	complex a(3.0,4.0);
	complex c;
	cout << "enter a complex number(q to quit): \n";
	while(cin >> c)
	{
		cout << "c is " << c << endl;
		cout << "complex conjugate is " << ~c <<endl;
		cout << "a is " << a << endl;
		cout << "a + c is "<<a + c << endl;
		cout << "a -c  is " << a - c << endl;
		cout << "a * c" << a * c <<endl;
		cout << "2 *c is " << 2 *c << endl;
		cout << "enter a complex number (q to quit):" << endl;
	}
	cout << "done!" << endl;
	return 0;
}




运行结果:



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值