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;
    }
  • 相关阅读:
    Win10下访问linux的ext4分区文件并拷贝
    Zsh 无法找到自己的anaconda python
    Motrix 代替迅雷下载 aria2的配置
    Bash与python混合编程
    如何在 非系统盘安装 wsl
    Python_01
    CC2541蓝牙学习——通用I/O口中断
    自定义弹窗
    使用windbg搜索命令辅助逆向杀软穿透驱动注册表操作
    IAT Hook
  • 原文地址:https://www.cnblogs.com/ttzz/p/10573483.html
Copyright © 2011-2022 走看看