我为我的计算机科学课用 Python 编写了一个分数加法器。但是,我在最终答案缩减过程中遇到了问题。
该过程在 for 循环开始时使用“不等于”比较运算符 != 来测试分子和分母相除时是否会出现余数。如果有余数(分子 % 分母 ≠ 0),则执行该过程:每个值除以 n,然后 n 递增,并且 for 循环再次运行。这一直持续到它们彼此平均分配为止。
首先,我收到语法错误:
python FractionAdder.py 2 4 6 8
File "FractionAdder.py", line 23
for ansnum % n != 0 and ansdenom % n != 0:
^
SyntaxError: invalid syntax
其次,for循环并不完全健壮。我的预期目的是让它将最终答案简化为最简单的形式,但现在,它只是继续递增 n 并减少,直到分子和分母彼此均匀划分。这是一个问题:3 能被 6 整除,但 3/6 并不是最简单的形式。我可以对如何提高程序的稳健性提出一些建议,以便 n 继续递增并且循环不断循环直到实现最简单的形式? (是否有更好的方法来构建我的条件来实现此目的?)
完整代码:
import sys
num1 = int(sys.argv[1])
denom1 = int(sys.argv[2])
num2 = int(sys.argv[3])
denom2 = int(sys.argv[4])
n = 1
# Find common denominators and adjust both fractions accordingly.
while denom1 != denom2:
denom1 = denom1 * denom2
num1 = num1 * denom2
denom2 = denom2 * denom1
num2 = num2 * denom2
# Add the numerators and set the ansdenom (denom1 and denom2 should be equal by this point if LCD function worked)
ansnum = num1 + num2
ansdenom = denom1
# Reduce the answer.
n = 2
for ansnum % n != 0 and ansdenom % n != 0:
ansnum = ansnum / n
ansdenom = ansdenom / n
n += 1
print("The sum of the two fractions is:" + str(ansnum) + "//" + str(ansdenom))
提前致谢!
最佳答案
您看到的错误是由于 for
的错误使用而产生的,其中 while
是正确的循环类型(for
是 for 迭代, while
表示条件)。
尽管如此,您决定公分母的逻辑是有缺陷的,并导致无限循环。请阅读 least common multiple ,并考虑以下伪代码来确定"new"分子:
lcm = lcm(den1, den2)
num1 *= lcm / den1
num2 *= lcm / den2
关于python - 这个简单的 Python 分数加法器并不完全健壮,并且会收到错误。如何改进?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46229543/