Python 函数没有 return 任何值

Python function doesn't return any values

它适用于某些值(例如“100 12 2”),但由于某种原因在“102 12 2”时失败。 在 Windows 和具有不同 python 版本的 MacOS 上进行了检查,结果相同并且不受设置的影响。

from math import floor

s, x, y = 102, 12, 2

def calc(s, x, y):
    q = 0
    if x > y:
        while s - (s / x) > 0:
            q += s / x
            q1 = s / x
            s = s - (s / x) * x
            s += q1 * y
        return floor(q)
    else:
        return 'Inf'

if type(calc(s, x, y)) is int:
    print(calc(s, x, y))
else:
    print('Inf')

尝试将条件中的零替换为较小的数字,例如1e-16:

from math import floor

s, x, y = 102, 12, 2

def calc(s, x, y):
    q = 0
    if x > y:
        while s - (s / x) > 1e-16:
            q += s / x
            q1 = s / x
            s = s - (s / x) * x
            s += q1 * y
        return floor(q)
    else:
        return float('Inf')

print(calc(s, x, y)) # 10

这样做的原因是序列s - s/x不会正好变成零;它只会任意接近于零。 (即使代数上保证精确为零,浮点数也存在固有的不精确性,所以无论如何你都需要一些阈值。)