如何比较单个(浮点)类型? [英] How to compare single (floating point) types?
问题描述
我的场景中有6个InputField。他们的内容类型是十进制。
I have 6 InputFields in my scene. Their content type is decimal.
我从这些输入字段中获取值,并检查它们的总和是否等于100.02。我在所有参数中都输入了16.67。
I fetch values from these input fields and check if their sum is equal to 100.02. I enter 16.67 in all of them.
float fireP = float.Parse(firePercentage.text);
float waterP = float.Parse(waterPercentage.text);
float lightP = float.Parse(lightPercentage.text);
float nightP = float.Parse(nightPercentage.text);
float natureP = float.Parse(naturePercentage.text);
float healthP = float.Parse(healthPercentage.text);
float total = fireP + waterP + lightP + nightP + natureP + healthP;
if (total == 100.02f)
{
Debug.Log("It's equal");
}
else
{
Debug.Log(" Not equal. Your sum is = " + total);
}
我在控制台中收到不相等。您的总和= 100.02日志。
无论如何都知道为什么会发生这种情况?
I am getting " Not equal. Your sum is = 100.02" in my console log. Anyways has any idea why this might be happening ?
推荐答案
最接近 16.67的
是 float
16.6700000762939453125
。
最近的 float
至 100.02
是 100.01999664306640625
前者自身5次与后者完全不同,因此它们将不相等。
Adding the former to itself 5 times is not exactly equal to the latter, so they will not compare equal.
在此特殊情况,将 tolerance 与1e-6的顺序进行比较可能是可行的方法。
In this particular case, comparing with a tolerance in the order of 1e-6 is probably the way to go.
这篇关于如何比较单个(浮点)类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!