第八周实验报告3

实现分数类中的运算符重载,在分数类中可以完成分数的加减乘除(运算后再化简)、求反、比较(6种关系)的运算。

#include<iostream>
#include<cmath>
using namespace std;
class CFraction
{
private:
	int nume;
	int deno;
public:
	CFraction(int n=0, int d=1) : nume(n), deno(d){} 
	CFraction operator + (CFraction &);
    CFraction operator - (CFraction &);
	CFraction operator * (CFraction &);
	CFraction operator / (CFraction &);
	CFraction operator -();
	void display();
	bool operator > (CFraction &);
	bool operator < (CFraction &);
	bool operator == (CFraction &);
};
CFraction CFraction::operator + (CFraction &a )
{
	CFraction n;
	n.nume = a.deno * nume + a.nume * deno;
	n.deno = deno * a.deno ;
	return n;
}

CFraction CFraction::operator - (CFraction &a)
{
	CFraction n;
	n.nume = a.deno * nume - a.nume * deno;
	n.deno = deno * a.deno ;
	return n;
}

CFraction CFraction::operator / (CFraction &a)
{
	CFraction n;
	n.nume = nume * a.deno ;
	n.deno = deno * a.nume ;
	return n;
}

CFraction CFraction::operator * (CFraction &a)
{
	CFraction n;
	n.nume = nume * a.nume ;
	n.deno = deno * a.deno ;
	return n;
}

CFraction CFraction::operator -()
{
	CFraction n;
	n.nume = -nume;
	n.deno = deno;
	return n;
}
	


void CFraction::display()
{
	int m, n, r, a, b;
	a = abs(nume);
	b = abs(deno);
	if( a > b)
	{
		m = a;
		n = b;
	}
	else
	{
		m = b;
		n = a;
	}
	r = m % n;
	while( r != 0)
	{
		m = n;
		n = r;
		r = m % n;
	}
	nume = nume / n;
	deno = deno / n;

 	cout << nume << "/" << deno << endl;
}

bool CFraction::operator > (CFraction &a)
{
	if( a.deno * nume > a.nume * deno)
	{
		return true;
	}
	else
	{
		return false;
	}
}

bool CFraction::operator < (CFraction &a)
{
	if( a.deno * nume < a.nume * deno)
	{
		return true;
	}
	else
	{
		return false;
	}
}
bool CFraction::operator == (CFraction &a)
{
	if( a.deno * nume < a.nume * deno)
	{
		return true;
	}
	else
	{
		return false;
	}
}

int main()
{
	CFraction c1(1,2), c2(1,3), c3;
	cout << "c1=";
	c1.display ();
	cout << "c2=";
	c2.display ();

	if( c1 > c2) cout << "c1>c2" << endl;
	if( c1 < c2) cout << "c1<c2" << endl;
	if( c1 == c2) cout << "c1=c2" << endl;
    cout << "-c1 = ";
	c3 = -c1;
	c3.display ();
	cout << "c1+c2=";
	c3 = c1 + c2;
	c3.display ();

	cout << "c1-c2=";
	c3 = c1 - c2;
	c3.display ();

	cout << "c1*c2=";
	c3 = c1 * c2;
	c3.display ();

	cout << "c1/c2=";
	c3 = c1 / c2;
	c3.display ();

	system("pause");
	return 0;
	
}





 

还好老师手下留情<<<就让做了三个

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值