把分数的几个基本操作封装到了一个命名空间里,支持输入,输出,乘法,加法,约分和取倒数,基于c++ STL中的pair实现,使用时调用函数即可,代码中有简略注释

简介

把分数的几个基本操作封装到了一个命名空间里,支持输入,输出,乘法,加法,约分和取倒数,基于c++ STL中的pair实现,使用时调用函数即可,代码中有简略注释

Code

#include<stdio.h>
#include<iostream>
#include<utility>
using namespace std;
namespace Frac
{
	#define mp make_pair
	#define pi pair<int,int>
	int gcd(int a,int b){return b?gcd(b,a%b):a;}//求gcd
	void reduc(pi &a)//约分
	{
		bool flag=0;
		if(a.first<0&&a.second<0) a.first=-a.first,a.second=-a.second;
		if(a.first<0) a.first=-a.first,flag=1;
		if(a.second<0) a.second=-a.second,flag=1;
		int ggcd=gcd(a.first,a.second);
		a.first/=ggcd;
		a.second/=ggcd;
		if(flag) a.first=-a.first;
	}
	void inv(pi &a){swap(a.first,a.second);}//取倒数
	pi add(pi a,pi b)//加法
	{
		pi ans;
		int ggcd=gcd(a.second,b.second);
		ans.second=a.second/ggcd*b.second;
		ans.first=a.second/ggcd*b.first+b.second/ggcd*a.first;
		return ans;
	}
	pi multi(pi a,pi b)//乘法
	{
		int gcd1=gcd(a.first,b.second),gcd2=gcd(a.second,b.first);
		a.first/=gcd1,b.second/=gcd1;
		a.second/=gcd2,b.first/=gcd2;
		return mp(a.first*b.first,a.second*b.second);
	}
	pi input()//输入
	{
		pi a;
		bool f;
		char c=getchar();
	    a.first=0,f=0;
	    while(c<48||c>57){if(c=='-')f=1;c=getchar();}
	    while(c>47&&c<58)a.first=a.first*10+(c^48),c=getchar();
	    if(f) a.first=-a.first;
	    c=getchar();
	    a.second=0,f=0;
	    while(c<48||c>57){if(c=='-')f=1;c=getchar();}
	    while(c>47&&c<58)a.second=a.second*10+(c^48),c=getchar();
	    if(f) a.second=-a.second;
	    return a;
	}
	void print(pi a)//输出
	{
		reduc(a);
		if(a.second==1) cout<<a.first;
		else if(a.first==0) cout<<0;
		else if(a.second==0)cout<<"Error!";
		else cout<<a.first<<'/'<<a.second;
	}
	#undef mp
	#undef pi
}

使用方法

在函数名前加上Frac::就可以调用了