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]}")