You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码陷入While循环求助:判断除法结果是否为整数

浮点数精度导致循环无法退出的问题解决

你的代码陷入死循环的核心原因是浮点数的二进制存储精度误差:

  • 0.1无法被二进制浮点数精确表示,每次执行riser += 0.1时,riser的实际值会出现微小偏差(比如15.1可能被存储为15.100000000000001)。
  • 这种偏差会导致x/riser的结果永远无法成为精确的整数,checkint始终为False,循环永远无法退出。

两种可行的修复方案:

方案1:用整数运算规避浮点数精度问题

把所有数值转换为整数单位(比如将厘米转为毫米),全程用整数计算,彻底避免精度误差:

print("Welcome to Straircase Calculater")
print("")

x_cm = float(input("Enter Floor Height = "))
# 转换为毫米,用整数计算
x_mm = int(x_cm * 10)

riser_mm = 150  # 对应15.0厘米
y = x_mm / riser_mm
checkint = y.is_integer()

while not checkint:
    riser_mm += 1  # 每次增加1毫米(对应0.1厘米)
    y = x_mm / riser_mm
    checkint = y.is_integer()

# 转换回厘米输出
print("Number of Steps = " + str(y))
print("Step Riser = " + str(riser_mm / 10))

方案2:允许微小误差的整数判断

不改变浮点数运算,但判断y是否接近整数(设置一个极小的误差阈值,比如1e-6),而不是要求完全精确:

print("Welcome to Straircase Calculater")
print("")

x = float(input("Enter Floor Height = "))

riser = 15.0
y = x / riser
# 检查y是否与整数的差值小于1e-6
is_close_to_int = abs(y - round(y)) < 1e-6

while not is_close_to_int:
    riser += 0.1
    y = x / riser
    is_close_to_int = abs(y - round(y)) < 1e-6

print("Number of Steps = " + str(round(y)))
print("Step Riser = " + str(riser))

内容的提问来源于stack exchange,提问作者elias qamar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 17:08:31