#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;

typedef long long LL;

LL gcd(LL a, LL b) {
    return b == 0 ? a : gcd(b, a % b);
}

struct Fraction {
    LL up, down; // 分子,分母
    void reduce() { // 分数约分
        if (down < 0) {
            down = -down;
            up = -up;
        }
        LL d = gcd(abs(up), down);
        up /= d;
        down /= d;
    }
    Fraction operator+(const Fraction &b) const {
        Fraction res;
        res.up = up * b.down + down * b.up;
        res.down = down * b.down;
        res.reduce();
        return res;
    }
    Fraction operator-(const Fraction &b) const {
        Fraction res;
        res.up = up * b.down - down * b.up;
        res.down = down * b.down;
        res.reduce();
        return res;
    }
    Fraction operator*(const Fraction &b) const {
        Fraction res;
        res.up = up * b.up;
        res.down = down * b.down;
        res.reduce();
        return res;
    }
    Fraction operator/(const Fraction &b) const {
        Fraction res;
        res.up = up * b.down;
        res.down = down * b.up;
        res.reduce();
        return res;
    }
    void print() {
        if (up == 0) printf("0");
        else if (down == 1) printf("%lld", up);
        else if (abs(up) > down) printf("%lld %lld/%lld", up / down, abs(up) % down, down);
        else printf("%lld/%lld", up, down);
    }
};

int main() {
    Fraction x = {0, 1};
    int n;
    scanf("%d", &n);
    while (n--) {
        int op;
        scanf("%d", &op);
        if (op == 0) {
            x.reduce();
            x.print();
            printf("\n");
        } else {
            int y;
            scanf("%d", &y);
            Fraction t = {y, 1};
            if (op == 1) x = x + t;
            if (op == 2) x = x - t;
            if (op == 3) x = x * t;
            if (op == 4) x = x / t;
        }
    }
    return 0;
}
## 模拟计算器## 题目描述请实现一个迷你计算器具体规则如下。计算器中存储着一个值 $x$最开始时 $x=0$之后读入 $n$ 条指令指令需要按顺序一条一条执行。指令包括如下几种:- 1 y:令 $x$ 的值加上整数 $y$;- 2 y:令 $x$ 的值减去整数 $y$;- 3 y:令 $x$ 的值乘上整数 $y$;- 4 y:令 $x$ 的值除以整数 $y$。- 0:输出当前 $x$ 的值如果

原文地址: https://www.cveoy.top/t/topic/b5oU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录