OJ 1677 Problem D 分数类的乘法

Description

封装一个分数类Fract,用来处理分数功能和运算,支持以下操作:

  1. 构造:传入两个参数n和m,表示n/m;分数在构造时立即转化成最简分数。
  2. show()函数:分数输出为“a/b”或“-a/b”的形式,a、b都是无符号整数。若a为0或b为1,只输出符号和分子,不输出“/”和分母。
  3. 在分数类上重载乘法运算符,进行分数的乘法运算

你设计一个Fract类,使得main()函数能够运行并得到正确的输出。调用格式见append.cc

Input

输入多行,每行四个整数n、m、q、p,分别为两个分数n/m和q/p,至EOF结束。输入的分母不会为0;

Output

每行输出一个分数,为n/m和q/p的乘积,与输入顺序一致。
分数输出时为最简形式,负号只会出现在最前面,若分母为1或分子为0,则只输出一个整数,即分子部分,而没有“/”和分母部分。

Sample Input

1 3 2 3 
20 -15 150 80
0 77 -9 1
6 6 4 4 
12 16 4 3
-33 -48 6 11
0 -10 360 12

Sample Output

2/9
-5/2
0
1
1
3/8
0

Append Code

int main()
{
    int n, m, p, q;
    while(cin >> n >> m >> q >> p)
    {
        Fract f1(n, m), f2(q, p);
        Fract fr = f1 * f2;
        fr.show();
    }
}

AC代码

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
using namespace std;

int GreatestCommonDivisor(int a, int b) {
    return b == 0 ? a : GreatestCommonDivisor(b, a % b);
}
class Fract {
private:
    int a, b;
public:
    Fract(int aa, int bb) : a(aa / GreatestCommonDivisor(aa, bb)), b(bb / GreatestCommonDivisor(aa, bb)) {}
    void show() const {
        if(a == 0 || b == 1) printf("%d\n", a);
        else {
            if(a*b >= 0) { printf("%d/%d\n", (int)fabs(a), (int)fabs(b)); }
            else { printf("-%d/%d\n", (int)fabs(a), (int)fabs(b)); }
        }
    }
    operator double() {
        if(a == 0) return 0;
        else return (double)a / (double)b;
    }
    Fract& operator*(Fract& f) {
        a *= f.a;
        b *= f.b;
        int aa = a, bb = b;
        a /= GreatestCommonDivisor(aa, bb);
        b /= GreatestCommonDivisor(aa, bb);
        return *this;
    }
};

int main()
{
    int n, m, p, q;
    while(cin >> n >> m >> q >> p)
    {
        Fract f1(n, m), f2(q, p);
        Fract fr = f1 * f2;
        fr.show();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值