程序不能输入if语句 [英] Program not entering if statement
本文介绍了程序不能输入if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
x = -5
while x < 5:
if(x == 0):
print 0
x + = .01
这个程序不会输出任何内容。
但是,将最后一行改为x + = .5会使程序输出为0.什么是问题?
解决方案
浮点数表示可能不够准确。你绝对不应该测试零相等性,而应该使用沿着/ b
$ b
if(abs(x)<1E-10)的东西。 。
In my python program, an if statement is not being entered. I have simplified the code to the following:
x = -5
while x < 5:
if (x == 0):
print 0
x += .01
This program does not output anything.
However, changing the last line to x += .5 makes the program output 0. What's the problem?
解决方案
Floating point number representation might not be accurate enough. You should never test for zero equality but instead use something along
if (abs(x) < 1E-10) ...
这篇关于程序不能输入if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文