小编Ren*_*ené的帖子

在循环内修改变量时测试数字相等性

我是python的新手,我写的是:

t = 0.  
while t<4.9:  
    t = t + 0.1  
    if t == 1.:
        ... do something ...
Run Code Online (Sandbox Code Playgroud)

我注意到if语句从未被执行过.所以我修改了代码看起来像这样:

''' Case a'''
t = 0.  
while t<4.9:  
    t = t + 0.1  
print(t)
print(t == 5.)
Run Code Online (Sandbox Code Playgroud)

当我运行这个时,我得到:

>>> ================================ RESTART ================================
>>>  
5.0  
False  
Run Code Online (Sandbox Code Playgroud)

这是一个惊喜,因为我希望比较测试为True.然后,我尝试了以下两种情况:

''' Case b'''
t = 0
while t<5:
    t = t + 1
print(t)
print(t == 5)

''' Case c'''
t = 0.
while t<5:
    t = t + 0.5
print(t)
print(t == 5) …
Run Code Online (Sandbox Code Playgroud)

python floating-point

4
推荐指数
1
解决办法
408
查看次数

标签 统计

floating-point ×1

python ×1