模拟计算器

题目描述

请实现一个迷你计算器,具体规则如下。 计算器中存储着一个值 $x$,最开始时 $x=0$,之后读入 $n$ 条指令,指令需要按顺序一条一条执行。指令包括如下几种:

  • '1' y:令 $x$ 的值加上整数 $y$;
  • '2' y:令 $x$ 的值减去整数 $y$;
  • '3' y:令 $x$ 的值乘上整数 $y$;
  • '4' y:令 $x$ 的值除以整数 $y$。
  • '0':输出当前 $x$ 的值,如果 $x$ 是整数,直接输出;如果 $x$ 不是整数,输出其最简(假)分数表示。

输入格式

从标准输入读入数据。 第一行一个正整数 $n$($n≤10^4$)。 接下来 $n$ 行,每行输入一个整数 $z$($z∈[0..4]$),代表一条命令。当 $z∈[1..3]$ 时,紧接着输入一个整数 $y$,$y∈[-20..20]$;当 $z=4$ 时,紧接着输入一个整数 $y$,$y∈[-20..20]∧y≠0$。 保证计算过程中任意一条命令后,需要存储的最简分数的分子与分母的值均不会超过 $2^{50}$。

输出格式

输出到标准输出。 对于每个需要输出的操作,按要求输出一行应当输出的内容。 对于分数,按照 'p/q''-p/q' 的格式输出,其中 $p$ 是分子,$q$ 是分母,且需要保证 $p$ 和 $q$ 是互质的(即保证是最简分数)。

样例 #1

样例输入 #1

12
0
1 3 
3 5
0
4 -7
0
2 2
0
4 4
0
3 4
0

样例输出 #1

0
15
-15/7
-29/7
-29/28
-29/7

写一个C++代码内容:```cpp #include #include #include

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)
    {
        up = -up;
        down = -down;
    }
    LL d = gcd(abs(up), abs(down));
    up /= d;
    down /= d;
}

Fraction operator+(const Fraction &t) const
{
    Fraction f;
    f.up = up * t.down + t.up * down;
    f.down = down * t.down;
    f.reduce();
    return f;
}

Fraction operator-(const Fraction &t) const
{
    Fraction f;
    f.up = up * t.down - t.up * down;
    f.down = down * t.down;
    f.reduce();
    return f;
}

Fraction operator*(const Fraction &t) const
{
    Fraction f;
    f.up = up * t.up;
    f.down = down * t.down;
    f.reduce();
    return f;
}

Fraction operator/(const Fraction &t) const
{
    Fraction f;
    f.up = up * t.down;
    f.down = down * t.up;
    f.reduce();
    return f;
}

void print()
{
    if (up < 0) cout << '-';
    if (down == 1) cout << abs(up) << endl;
    else if (abs(up) > down) cout << abs(up) / down << ' ' << abs(up) % down << '/' << down << endl;
    else cout << abs(up) << '/' << down << endl;
}

};

int main() { int n; cin >> n;

Fraction res;
res.up = 0, res.down = 1;

while (n -- )
{
    int op;
    cin >> op;

    if (op == 0)
    {
        res.reduce();
        res.print();
    }
    else
    {
        int y;
        cin >> y;

        Fraction t;
        t.up = y, t.down = 1;

        if (op == 1) res = res + t;
        else if (op == 2) res = res - t;
        else if (op == 3) res = res * t;
        else res = res / t;
    }
}

return 0;

}

模拟计算器 - C++ 代码实现及分数运算

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

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