星空's Blog
星空's Blog
PAT-A1088 Rational Arithmetic

原题

Rational Arithmetic (20 分)

题解

这题真是。。。一言难尽
做起来特别蛋疼,C++的string不像Java那样可以用split进行分割,所以处理输入要花费一些功夫
剩下的难点就是结果表示
需要注意题目要求把假分数给转化为带分数,且真分数部分为最简形式,比如 9/6 -> 3/2
这里需要用到辗转相除法求最大公因数
剩下的就是格式的处理了,比较蛋疼的是
int a = 1;
a + "1" 不是string类型,必须用 to_string(a) + "1"才可以

代码

#include <iostream>
#include <string>
using namespace std;

long hcf(long a,long b) {
    int c = b;
    while (a % b != 0) {
        c = a % b;
        a = b;
        b = c;
    }
    return c;
}

string p(long a,long b) {
    bool isNegative = false;
    bool hasExtraInt = false;
    long c = 0;
    if (a < 0) {
        isNegative = true;
        a = -a;
    }
    if (b == 0) {
        return "Inf";
    }
    if (a % b) {
        if (a > b) {
            hasExtraInt = true;
            c = a / b;
            a = a % b;
        }
        long h = hcf(a,b);
        if (h > 1) {
            a = a / h;
            b = b / h;
        }
    }
    if (isNegative) {
        if (hasExtraInt) {
            return "(-" + to_string(c) + " " + to_string(a) + "/" + to_string(b) + ")";
        }
        return "(-" + (a % b == 0 ? to_string(a / b) : to_string(a) + "/" + to_string(b)) + ")";
    } else {
        if (hasExtraInt) {
            return to_string(c) + " " + to_string(a) + "/" + to_string(b);
        }
        return a % b == 0 ? to_string(a / b) : to_string(a) + "/" + to_string(b);
    }
}

int main(void) {
    string a,b;
    cin >> a >> b;
    long a1,a2,b1,b2,t1,t2;
    a1 = stoi(a.substr(0,a.find("/")));
    b1 = stoi(a.substr(a.find("/") + 1));
    a2 = stoi(b.substr(0,b.find("/")));
    b2 = stoi(b.substr(b.find("/") + 1));
    t1 = 0;
    t2 = 0;

    //加 
    t2 = b1 * b2;
    t1 = a1 * b2 + a2 * b1;
    cout << p(a1,b1) << " + " << p(a2,b2) << " = " << p(t1,t2) << endl;
    //减
    t2 = b1 * b2;
    t1 = a1 * b2 - a2 * b1;
    cout << p(a1,b1) << " - " << p(a2,b2) << " = " << p(t1,t2) << endl;
    //乘
    t1 = a1 * a2;
    t2 = b1 * b2;
    cout << p(a1,b1) << " * " << p(a2,b2) << " = " << p(t1,t2) << endl;
    //除
    t1 = a1 * b2;
    t2 = a2 * b1;
    if (t2 < 0) {
        t1 = -t1;
        t2 = -t2;
    }
    cout << p(a1,b1) << " / " << p(a2,b2) << " = " << p(t1,t2) << endl;
    return 0;
}
所有文章禁止转载。
代码仅供参考
为了对抗广告机器人,首次留言将会被审核
首页      算法学习      PAT-A      PAT-A1088 Rational Arithmetic
https://secure.gravatar.com/avatar/271861a23dcdde929d3ee8cb8c04f854?s=256&d=monsterid&r=g

星空

文章作者

发表评论

textsms
account_circle
email

星空's Blog

PAT-A1088 Rational Arithmetic
原题 Rational Arithmetic (20 分) 题解 这题真是。。。一言难尽 做起来特别蛋疼,C++的string不像Java那样可以用split进行分割,所以处理输入要花费一些功夫 剩下的难点就是结果表示 需…
扫描二维码继续阅读
2019-08-28
分类
标签云