鱼C论坛

 找回密码
 立即注册
查看: 1547|回复: 1

[技术交流] 0019-编程打卡:手动实现分数加减器

[复制链接]
发表于 2022-9-7 17:58:56 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 不二如是 于 2022-9-7 18:50 编辑

001.png
002.png
003.png
004a.png

一星答案:
def multiple(x2,y2):                         #求最小公倍数
    if x2 == 0 or y2 == 0:
        print("分母不能为“0”!")
    else:
        if x2 % y2 == 0:
            z2 = x2
        elif y2 % x2 == 0:
            z2 = y2
        else:
            z2 = x2 * y2
    return z2

def reduction(z1,z2):                          #约分并返回结果
    for i in range(z1, 1, -1):
        if z2 % i == 0 and z1 % i == 0:
            z2, z1 = int(z2 / i), int(z1 / i)
    if z2 == 1:
        result = z1
    elif z1 ==0:
        result = 0
    else:
        result = str(z1) + '/' + str(z2)
    return result

def get_num(str1):                           #获取分子分母
    if '/' in str1:
        x1,x2 = int(str1.split('/')[0]), int(str1.split('/')[1])
        return x1,x2
    else:
        x1,x2 = int(str1),1
        return x1,x2

def add_num(num1,num2):                      #加法
    x1, x2 = get_num(num1)
    y1, y2 = get_num(num2)
    z2 = multiple(x2,y2)
    z1 = int(x1 * z2 / x2 + y1 * z2 / y2)
    return reduction(z1,z2)

def sub_num(num1,num2):                       # 减法
    x1, x2 = get_num(num1)
    y1, y2 = get_num(num2)
    z2 = multiple(x2,y2)
    z1 = int(x1 * z2 / x2 - y1 * z2 / y2)
    return reduction(z1,z2)

if __name__ == '__main__':
    num1 = input("请输入第一个数,分数请使用“a/b”:")
    num2 = input("请输入第一个数,分数请使用“a/b”:")
    calc = input("请输入运算方法“+”或“-”")
    if calc == '+':
        result = add_num(num1,num2)
    elif calc == '-':
        result = sub_num(num1,num2)
    print("{} {} {}的运算结果为:{}".format(num1, calc, num2, result))


二星答案:
def gcd(m, n):
    """辗转相除法,寻找n和m的最大公约数"""
    while n != 0:
        m, n = n, m % n
    return m
# 用公倍数处理,再除以最大公约数就可以相加了 (a*d)/(b*d) + (c*b)/(d*b)

def fadd(a, b, c, d):
    """分数加法,a/b + c/d """
    numerator = a*d + c*b   # 分子
    denominator = b*d      # 分母
    if numerator % denominator == 0:
        # 整除情况下打印整数
        print(numerator // denominator)
    else:
        divisor = gcd(numerator, denominator)
        print("%d / %d" % (numerator/divisor, denominator/divisor))

def fminus(a, b, c, d):
    """分数减法, a/b - c/d"""
    numerator = a*d - c*b
    denominator = b*d
    if numerator % denominator == 0:
        # 整除情况下打印整数
        print(numerator // denominator)
    else:
        divisor = gcd(numerator, denominator)
        print("%d / %d" % (numerator/divisor, denominator/divisor))

fadd(1, 2, 1, 2)


三星答案:

游客,如果您要查看本帖隐藏内容请回复


基础语法:



算法讲解:





本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-9-7 21:18:31 | 显示全部楼层
我的答案是:三星答案
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-28 18:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表