分数四则运算的实现

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;
    }
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值