Lua for循环不会完成所有迭代 [英] Lua for loop does not do all iterations
问题描述
我是lua的新手,我正在使用它来自动执行模拟程序中的一些任务。在我的脚本中我有这种类型的for循环:
I am new to lua, and i am using it to automate some tasks in the simulation program femm. In my script i have this type of for loop:
for i=0.1,0.3,0.1
do
print(i)
end
问题是它只从0.1到0.2迭代(它没有输入i = 0.3)。我尝试了其他值(例如从0.1到0.4)并且它正常工作。为什么会发生这种奇怪的行为?这是一个浮点数问题吗?
The problem is it only iterates from 0.1 to 0.2(it does not enter i=0.3).I tried with other values (for example from 0.1 to 0.4) and it works properly. Why does this strange behaviour happen? Is this a floating point number problem?
推荐答案
这种情况发生的原因是,添加0.1到0.1三次产生的数字略大于0.3。因此,循环在到达目标结束号之前停止。
This happens because adding 0.1 to 0.1 three times produces a number that is slightly greater than 0.3. Hence the loop stops before reaching your target end number.
这是使用浮点值进行循环迭代的危险。改为以整数重写循环,并执行除法以获得所需的数字:
This is the danger of using floating point values for loop iteration. Rewrite the loop in integers instead, and perform a division to get your required number:
for j = 1,3
do
i = j/10
print(i)
end
这篇关于Lua for循环不会完成所有迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!