编写Python程序,实现n个分数相加,需要化简,不允许使用fraction
时间: 2023-05-16 12:07:41 浏览: 113
python 实现两数相加
非常感谢您的提问!以下是一个实现n个分数相加并化简的Python程序,不使用fraction模块:
```python
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
def lcm(a, b):
return a * b // gcd(a, b)
def add_fractions(fractions):
lcm_denominator = 1
numerator_sum = 0
for fraction in fractions:
lcm_denominator = lcm(lcm_denominator, fraction[1])
for fraction in fractions:
numerator_sum += fraction[0] * (lcm_denominator // fraction[1])
gcd_num_den = gcd(numerator_sum, lcm_denominator)
numerator_sum //= gcd_num_den
lcm_denominator //= gcd_num_den
return (numerator_sum, lcm_denominator)
n = int(input("请输入分数个数:"))
fractions = []
for i in range(n):
numerator, denominator = map(int, input("请输入第{}个分数的分子和分母,用空格隔开:".format(i+1)).split())
fractions.append((numerator, denominator))
result = add_fractions(fractions)
print("相加并化简后的结果为:{}/{}".format(result[0], result[1]))
```
如果您有任何问题或需要进一步的帮助,请随时告诉我。
阅读全文