Description
定义分数类,数据成员a和b表示分数的分子和分母,类中定义成员函数能够实现分数的加、减、乘和除运算。
Input
首先是一个正整数n,表示有n组数据。每一组数据中由4个整型数组成,分别表示第1个分数的分子和分母和第2个分数的分子和分母。
Output
两个分数加、减、乘和除的结果。
Sample Input
3
2 -4 3 5
1 2 3 4
4 3 2 -1
Sample Output
(1/10)(-11/10)(-3/10)(-5/6)
(5/4)(-1/4)(3/8)(2/3)
(-2/3)(10/3)(-8/3)(-2/3)
参考代码:
#include<iostream>///分数四则运算
#include<cmath>
using namespace std;
class fraction
{
public:
int above;
int below;
void reduction();
void makeCommond(fraction&);
public:
fraction(int a=0,int b=1)
{
above=a;
below=b;
}
fraction add(fraction);
fraction sub(fraction);
fraction mul(fraction);
fraction div(fraction);
void display();
};
void fraction::reduction()
{
int a,b,temp;
if(below<0)
{
above=-above;
below=-below;
}
a=abs(above);
b=abs(below);
while(a%b)
{
temp=a;
a=b;
b=temp%b;
}
above/=b;
below/=b;
}
void fraction::makeCommond(fraction& b)
{
int temp;
reduction();
b.reduction();
above*=b.below;
b.above*=below;
temp=below*b.below;
below=b.below=temp;
}
fraction fraction::add(fraction b)
{
fraction temp;
makeCommond(b);
temp.above=above+b.above;
temp.below=below;
temp.reduction();
return temp;
}
fraction fraction::sub(fraction b)
{
fraction temp;
makeCommond(b);
temp.above=above-b.above;
temp.below=below;
temp.reduction();
return temp;
}
fraction fraction::mul(fraction b)
{
fraction temp;
temp.above=above*b.above;
temp.below=below*b.below;
temp.reduction();
return temp;
}
fraction fraction::div(fraction b)
{
fraction temp;
temp.above=above*b.below;
temp.below=below*b.above;
temp.reduction();
return temp;
}
void fraction::display()
{
reduction();
cout<<'('<<above<<"/"<<below<<')';
}
int main()
{
int n;
cin>>n;
while(n--)
{
fraction f1,f2;
cin>>f1.above>>f1.below>>f2.above>>f2.below;
fraction f3=f1.add(f2);
fraction f4=f1.sub(f2);
fraction f5=f1.mul(f2);
fraction f6=f1.div(f2);
f3.display();
f4.display();
f5.display();
f6.display();
cout<<endl;
}
}