很简单但困扰我很久的问题:1/a+1/b=1/6,五个答案,为什么只有跑出四个?到底哪里错了?
初始化一个列表来存储解
solutions = []
遍历可能的 a 和 b 的值
for a in range(6, 100): # 从 6 开始遍历
for b in range(a, 100): # b 从 a 开始,因为 a 和 b 是无序的,且我们不想重复计算
if 1/a + 1/b == 1/6:
solutions.append((a, b))
打印所有解
for solution in solutions:
print(f”a = {solution[0]}, b = {solution[1]}”)
#解1、a=7,b=42;解2、a=8,b=24;解3、a=9,b=18;解4、a=10,b=15;解5、a=12,b=12。解4就是跑不出来,到底是哪里错了呢?
1/10 = 0.1
1/15 = 0.06666666666666667
1/6 = 0.16666666666666666
精度问题吧,经常会出现这样的问题。
楼主使用下面的方法,避免计算过程中出现浮点数运算, 就能得到你期望的解。
看到你这个问题挺有意思,我就尝试着回答一下。
改成整數的比對,
(a + b) * 6 == a * b
就不會出現誤差問題了 !精度问题,可以使用decimal
精度问题 可以使用from fractions import Fraction
浮点数精度问题 solutions = []
for a in range(6, 100): for b in range(a, 100):
for solution in solutions: print(f"a = {solution[0]}, b = {solution[1]}")