我正在测试一个简单的线性丢番图方程代码。这是代码:
a = 3
b = 4
n = 67
i = 0
while True:
if i * a <= n:
if (n - (i * a)) % b == 0:
yy = int((n - (i * a)) / b)
print("{0} x {1} + {2} x {3} = {4}".format(a, i, b, yy, n))
i = i + 1
else:
print("No possible solution!")
break
当代码运行时,它能够在这个方程中找到可能的 x 和 y(这很好)。但是,我想不通的是为什么打印“没有可能的解决方案!” 正在与答案一起打印。假设 else 块仅在无法解决的情况下出现,例如 a = 3、b = 4 和 n = 2。
任何建议将被认真考虑。
print("No possible solution!")
在 else 情况下,因此无论是否找到任何解决方案,它都会执行。
这是修复它的一种方法,其中布尔变量跟踪是否找到解决方案并根据该变量的状态打印消息:
a = 3
b = 4
n = 2
i = 0
solution_found = False
while True:
if i * a <= n:
if (n - (i * a)) % b == 0:
yy = int((n - (i * a)) / b)
print("{0} x {1} + {2} x {3} = {4}".format(a, i, b, yy, n))
solution_found = True
i = i + 1
else:
break
if not solution_found:
print("No possible solution!")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句