C++ 实现分数的四则运算

时间:2021-03-10 20:40:24

对分数求加减乘除,以及化简

#include<iostream>
#include<math.h>
using namespace std;
struct Fraction{
    long  up,down;
};
//求分子分母的最大公约数
int gcb(int a,int b)
{
    if(b==0)
        return a;
    else
        return gcb(b,a%b);
}
//化简
Fraction reduction(Fraction &result)
{
    if(result.down < 0)  //分母为负
    {
        result.down = -result.down;
        result.up = - result.up;
    }
    else if(result.up == 0)  //分母为0
        result.down = 1;
    else
    {
        int x = gcb(abs(result.up),abs(result.down));  //分子分母同时除最大公约数
        result.up /= x;
        result.down /= x;
    }
    return result;
}
//加法
Fraction Add(Fraction a,Fraction b)
{
    Fraction c;
    c.up = a.up * b.down + a.down * b.up;
    c.down = a.down * b.down;
    return reduction(c);
}
//减法
Fraction minu(Fraction a,Fraction b)
{
    Fraction c;
    c.up = a.up * b.down - a.down * b.up;
    c.down = a.down * b.down;
    return reduction(c);
}
//乘法
Fraction multi(Fraction a,Fraction b)
{
    Fraction c;
    c.up = a.up * b.up;
    c.down = a.down * b.down;
    return reduction(c);
}
//除法
Fraction divide(Fraction a,Fraction b)
{
    Fraction c;
    c.up = a.up * b.down;
    c.down = a.down * b.up;
    return reduction(c);
}
void showresult(Fraction result)
{
    if(result.down == 1)
        cout<<result.up<<endl;
    else if(abs(result.up)>abs(result.down))
        cout<<result.up /result.down <<" "<<abs(result.up % result.down)<<"/"<<result.down<<endl;
    else
        cout<<result.up<<"/"<<result.down<<endl;
}
int main()
{
    Fraction f1,f2;
    while(cin>>f1.up>>f1.down>>f2.up>>f2.down)
    {
        showresult(Add(f1,f2));
        showresult(minu(f1,f2));
        showresult(multi(f1,f2));
        showresult(divide(f1,f2));
    }
    return 0;
}