pat乙级1034 有理数四则运算 (20 分) python fractions库做法

本文介绍了如何使用Python的fractions库进行有理数计算,强调了输入和输出应保持为最简带分数形式,同时指出了常见错误点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
在这里插入图片描述
fractions库是一个分数计算有关的库 可以执行分数的计算 输出也是分数
易错点:输入的两个数 最终也要化为最简的带分数
带分数:在这里插入图片描述
代码如下

from fractions import Fraction
m, n = input().split()
m, n = Fraction(m), Fraction(n)#转化为库的分数形式 会自动化简到最简分数
def fraction_to_mixed_number(fraction):
    if "/" not in str(fraction) or abs(fraction) < 1:#如果是个整数 或者绝对值小于一 就不用换成带分数
        if fraction < 0:
            return '(' + str(fraction) + ')'
        else:
            return str(fraction)
    else:
        # 方法一分割字符串 分子分母整除
        # n1, n2 = map(int, str(abs(fraction)).split("/"))
        # if fraction < 0:
        #     return '(-' + str(n1 // n2) + ' ' + str(n1 % n2) + '/' + str(n2) + ')'
        # else:
        #     return str(n1 // n2) + ' ' + str(n1 % n2) + '/' + str(n2)
        # # 方法二
        if fraction < 0:
            fraction = abs(fraction)#取绝对值 因为//地板除方法是向下取整 %取余也是向下取整的取余 所以在负数是会出错
            return '(-' + str(fraction // 1) + ' ' + str(fraction % 1) + ')'
        else:
            return str(fraction // 1) + ' ' + str(fraction % 1)
result = [fraction_to_mixed_number(m + n), fraction_to_mixed_number(m - n), fraction_to_mixed_number(m * n),"啦啦啦"]
if n != 0:
    result[3]=fraction_to_mixed_number(m / n)
else:
    result[3]="Inf"
print(f"{fraction_to_mixed_number(m)} + {fraction_to_mixed_number(n)} = {result[0]}")
print(f"{fraction_to_mixed_number(m)} - {fraction_to_mixed_number(n)} = {result[1]}")
print(f"{fraction_to_mixed_number(m)} * {fraction_to_mixed_number(n)} = {result[2]}")
print(f"{fraction_to_mixed_number(m)} / {fraction_to_mixed_number(n)} = {result[3]}")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值