zoukankan      html  css  js  c++  java
  • C++ 实现分数的四则运算

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

    #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;
    }
  • 相关阅读:
    微信证书发布涉及到的问题
    C# Timer自带定时器
    微信accesstoken回调
    c#数组乱序,打乱数组
    JS 数组乱序
    百度地图LBS开放平台AK一直没有用
    C# 微信支付证书使用
    提交失败问题一:检测到有潜在危险
    apache如何发布地图服务
    Java后端进阶教程
  • 原文地址:https://www.cnblogs.com/ttzz/p/10573483.html
Copyright © 2011-2022 走看看