Python3PTA乙1034有理数四则运算 (完美通过版)

风格不统一 提交于 2020-01-01 01:08:38

 注意事项:

  1. 减法运算中 ,为了避免分母前出现负号的情况,在处理时,将所有负数按其绝对值处理。最后再添负号
  2. 除法运算中,0 / 0输出结果是 Inf。逻辑判断时 0 / 0容易出现bug
  3. 在判断正负的时候,别用两个数乘积来判断。因为如果这两个数过大容易出现结果溢出情况

 

# coding:utf-8
def Num(s):
    N, k, F = 0, 0, 0
    if s[0] == '-':
        F = 1
        s[1:] = s[-1: 0: -1]
        s = s[1:]
    else:
        s[0:] = s[-1:: -1]
    for item in s:
        N += int(item) * 10 ** k
        k += 1
    if F == 0:
        return N
    else:
        return (N * -1)


def GCD(a, b):
    if a < b:
        a, b = b, a
    while b != 0:
        a, b = b, a % b
    return a


def Rationalized(m_a, d_a):  # 有理化
    flag = 0                #flag 为0表示 分子,分母同号
    if (m_a < 0 and d_a > 0) or (m_a > 0 and d_a < 0):
        flag = 1
        if m_a < 0 and d_a > 0:
            m_a = m_a * (-1)
        if m_a > 0 and d_a < 0:
            d_a = d_a * (-1)
    if d_a == 0:
        return ('Inf')
    elif m_a == 0:
        return ('0')  # 如果返回 (0), 在len()中 (0) 会被当作 int而报错
    else:
        num = int(m_a / d_a)
        remainder = abs(m_a) % abs(d_a)
        gcd = GCD(remainder, d_a)
        m = int(remainder / gcd)
        d = int(d_a / gcd)
        if num == 0 and m != 0:
            st = (("%d/%d") % (m, d))
        elif num == 0 and m == 0:
            st = ('0')
        elif num != 0 and m == 0:
            st = ("%d" % num)
        else:
            st = ("%d %d/%d" % (num, m, d))
    if flag == 1:
        st = (('(-') + st + (')'))
    return st


s1, s2 = input().split()
Mol_1, Den_1 = s1.split('/')
Mol_2, Den_2 = s2.split('/')
Mol_1 = list(Mol_1)
Den_1 = list(Den_1)
Mol_2 = list(Mol_2)
Den_2 = list(Den_2)

mol_1 = Num(Mol_1)
den_1 = Num(Den_1)
mol_2 = Num(Mol_2)
den_2 = Num(Den_2)
# 操作数与被操作数的有理化
num_1 = Rationalized(mol_1, den_1)
num_2 = Rationalized(mol_2, den_2)

#加
m_a = mol_1 * den_2 + mol_2 * den_1
d_a = den_1 * den_2
num_a = Rationalized(m_a, d_a)
# 打印加法结果
print(num_1 + ' + ' + num_2 + ' = ' + num_a)
# 减
m_a = mol_1 * den_2 - mol_2 * den_1
d_a = den_1 * den_2
num_a = Rationalized(m_a, d_a)
print(num_1 + ' - ' + num_2 + ' = ' + num_a)
# 乘
m_a = mol_1 * mol_2
d_a = den_1 * den_2
num_a = Rationalized(m_a, d_a)
print(num_1 + ' * ' + num_2 + ' = ' + num_a)
# 除
m_a = mol_1 * den_2
d_a = den_1 * mol_2
num_a = Rationalized(m_a, d_a)
print(num_1 + ' / ' + num_2 + ' = ' + num_a)


 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!