← 返回题库
初级

有理数四则运算

未完成
初级参考 完整示例代码供参考,建议自己理解后重新输入
def solve(a1, b1, a2, b2):
    from fractions import Fraction
    f1 = Fraction(int(a1), int(b1))
    f2 = Fraction(int(a2), int(b2))
    def fmt(f):
        if f.denominator == 1:
            return str(f.numerator)
        return f'{f.numerator}/{f.denominator}'
    print(f'{fmt(f1)} + {fmt(f2)} = {fmt(f1 + f2)}')
    print(f'{fmt(f1)} - {fmt(f2)} = {fmt(f1 - f2)}')
    print(f'{fmt(f1)} * {fmt(f2)} = {fmt(f1 * f2)}')
    print(f'{fmt(f1)} / {fmt(f2)} = {fmt(f1 / f2)}')

示例

输入
solve(2, 3, -4, 2)
期望输出
2/3 + -2 = -4/3
2/3 - -2 = 8/3
2/3 * -2 = -4/3
2/3 / -2 = -1/3
Python 代码 🔒 登录后使用
🔒

登录后即可练习

注册免费账号,在浏览器中直接运行 Python 代码