马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 不二如是 于 2022-9-7 18:50 编辑
一星答案:
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)
三星答案:
基础语法:
算法讲解:
|