C++基础练习-类与对象-创建复数类,建立初始化,相角,幅值,加减乘除函数

C++基础练习-类与对象

创建一个复数类complex,私有成员包括实部real和虚部imag,初始化使用
init成员函数,计算幅值使用amplitude成员函数,计算相角使用phase成员函数,
同时为complex定义加减乘除四则运算函数。

#include<iostream>																						
#include<math.h>													//包含pow(double,double),sqrt(double),atan(double)函数
using namespace std;
class Complex {
public:
	void init() {													//自建init初始化函数初始化复数的实部和虚部
		cout << "Please enter the real and imaginary parts of a complex number:" << endl;
		cin >> real;
		cin >> imag;
	}
	void amplitude();												//计算幅值和相角的两个成员函数
	void phase();
	void dp() {														//输出复数属性的函数
		cout << "real: " << real << " imag:  " << imag;
		cout << endl; amplitude(); phase(); cout << endl;
	}
	Complex operator+(Complex&col1);								//为complex定义加减乘除四则运算(运算符重载)
	Complex operator-(Complex&col1);
	Complex operator*(Complex&col1);
	Complex operator/(Complex&col1);
private:
	double real, imag;
};
void Complex::amplitude() {											//类外计算幅值,函数pow(x, y)计算x的y次幂,sqrt()为开方函数			
	cout << "The amplitude of the complex number is " << sqrt(pow(real, 2) + pow(imag, 2)) << endl;
}
void Complex::phase() {												//计算相角,用到了反正切函数atan()												
	if (real == 0 && imag == 0)
		cout << "Calculated phase nonsense!" << endl;
	else
		if (real > 0) {
			cout << "The phase of the complex number is " << atan(imag / real) << "degress." << endl;
		}
		else
			if (real = 0)
				cout << "The phase of the complex number is 90 degrees or -90 degrees." << endl;
			else
				if (real < 0 && imag != 0) {
					double deg1 = atan(imag / real) + 180;
					double deg2 = atan(imag / real) - 180;
					cout << "The phase of the complex number is " << deg1 << " degress or " << deg2 << " degress." << endl;
				}
				else {
					cout << "The phase of the complex number is 180 degrees" << endl;
				}
}
Complex Complex::operator+(Complex&col1)		//+ - * /四则运算(运算符重载)
{
	Complex col;
	col.real = real + col1.real;
	col.imag = imag + col1.imag;
	return col;
}
Complex Complex::operator-(Complex&col1)
{
	Complex col;
	col.real = real - col1.real;
	col.imag = imag - col1.imag;
	return col;
}
Complex Complex::operator*(Complex&col1)
{
	Complex col;
	col.real = real * col1.real;
	col.imag = imag * col1.imag;
	return col;
}
Complex Complex::operator/(Complex&col1)
{
	Complex col;
	col.real = real / col1.real;
	col.imag = imag / col1.imag;
	return col;
}
int main() {									//定义六个复数对象对成员函数进行验证
	Complex col1; col1.init(); col1.dp();
	Complex col2; col2.init(); col2.dp();
	Complex col3; col3 = col1 + col2; col3.dp();
	Complex col4; col4 = col1 - col2; col4.dp();
	Complex col5; col5 = col1 * col2; col5.dp();
	Complex col6; col6 = col1 / col2; col6.dp();
	return 0;
}
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值