面向对象部分_207

#include <iostream>
#include <cmath>


using namespace std;


class fraction
{
private:
    int m;
    int n;
public:
    fraction(){}
    fraction(int, int);
    int gcd(int, int);
    fraction operator+(const fraction&);
    fraction operator-(const fraction&);
    void show();
};


fraction::fraction(int im, int in)
{
    m = im;
    n = in;
}


int fraction::gcd(int x, int y)   //辗转相除法 如果不懂 可以自己找资料学习
{
    if (y == 0)
    {
        return x;
    }
    else
    {
        return gcd(y, x % y);
    }
}


fraction fraction::operator+(const fraction& b)  //最基本的分数相加 分母相乘 分子分别乘以另一个分母 然后相加 最后除去最大公约数
{
    fraction c;
    int t;
    c.m = b.n * m + n * b.m;
    c.n = n * b.n;
    if (fabs(c.m) > c.n)
    {
        t = gcd(fabs(c.m), c.n);
    }
    else
    {
        t = gcd(c.n, fabs(c.m));
    }
    c.m /= t;
    c.n /= t;
    return c;
}


fraction fraction::operator-(const fraction& b) //原理同上
{
    fraction c;
    int t;
    c.m = b.n * m - n * b.m;
    c.n = n * b.n;
    if (fabs(c.m) > c.n)
    {
        t = gcd(fabs(c.m), c.n);
    }
    else
    {
        t = gcd(c.n, fabs(c.m));
    }
    c.m /= t;
    c.n /= t;
    return c;
}


void fraction::show()  // 输出时应该考虑特殊情况 即0 和 1
{
    if (m == 0)
    {
        cout << "0" << endl;
    }
    else if (m / n == 1 || m / n == -1)
    {
        cout << m / n << endl;
    }
    else
    {
        cout << m << "/" << n << endl;
    }
}


int main()
{
    fraction a(-1, 3), b(3, 12), c, d;
    c = a + b;
    d = a - b;
    c.show();
    d.show();
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值