分数的表示和运算

分数的表示和运算

#include <cstdio>
#include <cmath>
//分数的表示和化简
struct fraction{
	int up,down;
}f[2];
int gcd(int a,int b)
{
	//if(b == 0)	return a;
	//else return gcd(b,a%b);
	return b==0?a:gcd(b,a%b);
}
fraction reduction(fraction result) //分数化简 
{	
	if(result.down < 0){
		result.up = -result.up;
		result.down = -result.down;
	}
	if(result.up == 0){
		result.down = 1;
	}
	else {
		int d = gcd(abs(result.up),abs(result.down));
		result.up /= d;
		result.down /= d;  
	}
	return result;
}
fraction minus(fraction f1,fraction f2)  //分数减法 
{
	fraction result;
	result.up = f1.up*f2.down-f1.down*f2.up;
	result.down = f1.down*f2.down;
	return result; 
}
fraction multi(fraction f1,fraction f2)  //分数乘法 
{
	fraction result;
	result.up = f1.up*f2.up;
	result.down = f1.down*f2.down;
	return result;
}
fraction divide(fraction f1,fraction f2) //分数除法 
{
	fraction result;
	result.up = f1.up*f2.down;
	result.down = f1.down*f2.up;
	return result;
}
void print_r(fraction f)  //显示分数 
{
	f = reduction(f);
	if(f.down == 1)	printf("%d\n",f.up);
	else
		printf("%d/%d\n",f.up,f.down);
}

int main()
{
	scanf("%d%d%d%d",&f[1].up,&f[1].down,&f[2].up,&f[2].down);
	fraction r;
	r=minus(f[1],f[2]);
	print_r(r);
	r=multi(f[1],f[2]);
	print_r(r);
	r=divide(f[1],f[2]);
	print_r(r);
	return 0;
} 


posted on 2018-01-22 10:27  七昂的技术之旅  阅读(232)  评论(0编辑  收藏  举报

导航