字符串转换为浮点数错误? (闪电战 - 反思)
我在 Blitzmax 中遇到了一个小问题。 我尝试读取 INI 文件,如果我读取浮点数,它们会以一种非常奇怪的方式进行转换。 相关文件中的行看起来像这样,例如:
_fStrength=40.6
该输出看起来像这样:
DebugLog:_fStrength: 40.5999985
我用来读取的代码与反射一起工作,看起来像这样:
For Local fld:TField = EachIn id.EnumFields()
fld.Set(obj, SearchInFile("TempWeapon" + index, fld.Name(), "Weapons.ini"))
DebugLog(fld.Name() + ": " + String(fld.Get(obj)))
Next
我发现,只有当后面的数字出现时才会发生这种情况“。”不等于 5 或 0。 我无法解释这种行为,因为如果我不使用反射,它就可以正常工作。
有人可以帮我吗?
I have a little Problem in Blitzmax.
I try to read an INI-file and if I read floats they are converted in a very strange way.
The line in the file which is concerned looks like that for example:
_fStrength=40.6
The Output of this looks like that:
DebugLog:_fStrength: 40.5999985
The code I use to read that works with reflection and looks like that:
For Local fld:TField = EachIn id.EnumFields()
fld.Set(obj, SearchInFile("TempWeapon" + index, fld.Name(), "Weapons.ini"))
DebugLog(fld.Name() + ": " + String(fld.Get(obj)))
Next
I found out, that this only happens if the number after the "." does not equal's 5 or 0.
I can't explain this behaviour, because if I do not use reflections, it works fine.
Could anyone help me please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能知道,您的计算机使用有限的大小以二进制代码存储数字。
40.6
以二进制扩展是一个周期序列(101000.1001100110011001100...
,无限),类似于当您尝试写下1/3 的数字时发生的情况
) 重复,因此无法准确表示,因此会出现舍入错误。你在这里得到的正确位数看起来像你使用的是单精度浮点数,你可以通过加倍来将错误进一步推回,但它不会消失。
作为参考,您可能会发现浮点维基百科很有帮助。
As you probably know, your computer stores numbers in binary code, using a limited size.
40.6
expanded in binary is a periodic sequence (101000.1001100110011001100...
, infinitely), similarly to what happens when you try to write down the digits of1/3
) repeating and thus can not be represented exactly, so you get rounding errors.The number of correct digits you get here looks like you are using single-precision floating point numbers, you can push the error further back by going to double, but it won't disappear.
As a reference, you might find Wikipedia on floating point helpful.