分数运算


/************************************************************************/
/* 求两个分数相加,方法:先求出两个分母的最小公倍数,再求分子和,最后约检结果                                                                     */
/************************************************************************/

#include <iostream>
using namespace std;

class Fract{
	int num,den;//分子numerator of a fraction 分母denominator
public:
	Fract(int n=0,int d=1){
		num=n;
		den=d;
	}

	int gcd(int m,int n);//最大公约数 greatest common divisor 
	Fract result(Fract f);
	void show();
};

int main(){
	Fract f1(1,5);
	f1.show();
	Fract f2(7,20),f3;
	f2.show();
	f3=f1.result(f2);
	f3.show();
	return 0;
}

int Fract::gcd(int m,int n){
		int r;
		if(m<n){
			r=m;
			m=n;
			n=r;
		}
		while(r=m%n){
			m=n;
			n=r;
		}
		cout<<n<<endl;
		return n;
}

Fract Fract::result(Fract f){
	Fract sum;
	sum.den=this->den*f.den;
	sum.num=this->num*f.den+this->den*f.num;
	int x=gcd(sum.num,sum.den);
	sum.num=sum.num/x;
	sum.den=sum.den/x;
	return sum;
	
}

void Fract::show(){
	cout<<num<<"/"<<den<<endl;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值