复数运算,实现加减乘除和幂运算(C++语法向)

本人在学习C++面向对象编程时的练习笔记,涉及到类对象、运算符重载、自定义数据类型运算等操作。
代码:

#include <iostream>
#include <cmath>
#include <Windows.h>
using namespace std;

//复数相关计算器

class Complex {
private:
	double real;    //实部
	double imag;    //虚部
public:
	friend ostream& operator<<(ostream& cout, Complex& c);
	Complex(double r, double i);
	Complex(const Complex &c);
	~Complex() {};
	Complex(double r);              //虚部操作
	Complex operator+(const Complex& c);
	Complex operator-(const Complex& c);
	Complex operator*(const Complex& c);
	Complex operator/(const Complex& c);
	inline double getR() { return this->real; }
	inline double getI() { return this->imag; }
	inline double CX(double r) { this->real = r; }
	inline double CY(double i) { this->imag = i; }
};

ostream &operator<<(ostream& cout, Complex& c) {
	cout << "(" << c.getR() << "," << c.getI() << ")";
	return cout;
}

Complex::Complex(double r, double i):real(r),imag(i){}

Complex::Complex(const Complex& c) {
	this->real = c.real;
	this->imag = c.imag;
}

Complex::Complex(double r) {
	this->imag = 0;
	this->real = r;
}

Complex Complex::operator+(const Complex& c) {
	return Complex(this->real + c.real, this->imag + c.imag);
}

Complex Complex::operator-(const Complex& c) {
	return Complex(this->real - c.real, this->imag - c.imag);
}

Complex Complex::operator*(const Complex& c) {
	return Complex(real * c.real - imag * c.imag, real * c.imag + c.real * imag);
}

Complex Complex::operator/(const Complex& c) {
	return Complex((double)(real * c.real + imag * c.imag) / (double)(c.real * c.real + c.imag * c.imag),
		(double)(imag * c.real - real * c.imag) / (double)(c.real * c.real + c.imag * c.imag));
}


Complex CPower(Complex& c, unsigned n) {  //暴力方法
	Complex resu(c);
	for (n; n > 1; n--) {
		resu = resu * c;
	}
	return resu;
}

Complex ComplexPower(Complex c1, double n) {    //利用棣莫弗公式求乘方
	double abs_c1 = sqrt(c1.getR() * c1.getR() + c1.getI() * c1.getI());
	double theta = atan(c1.getI() / c1.getR());
	
	cout << abs_c1 << endl;
	theta = theta*n;
	abs_c1 = pow(abs_c1, n);

	cout << abs_c1 << "\tcos(theta) = " << cos(theta) << "\tsin(theta) = " << sin(theta) << endl;
	return Complex(abs_c1 * cos(theta), abs_c1 * sin(theta));
}

int main() {
	Complex c1(1, 2);
	Complex c2(0.3,-1.3);
	Complex cr = CPower(c1, 5);
	cout << "cr = (" << cr.getR() << "," << cr.getI() << ")" << endl;
	Complex cr2 = ComplexPower(c2, 3);

	cout << "cr2 = (" << cr2.getR() << "," << cr2.getI() << ")" << endl;

	cout << pow(1.23, 3.01) << endl;
	//框架:构造出来两个复数,利用运算符重载输出加减乘除
	//    利用虚函数继承计算传入的实数和复数的运算
	Complex cr3 = c1 + c2;
	cout << cr3 << endl;
	
	system("pause");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cloud Stream

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值