问题描述
我的场景中有 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
.
离100.02
最近的float
是100.01999664306640625
将前者与自身相加 5 次并不完全等于后者,因此它们比较起来不会相等.
Adding the former to itself 5 times is not exactly equal to the latter, so they will not compare equal.
在这种特殊情况下,以 1e-6 的顺序与容差进行比较可能是可行的方法.
In this particular case, comparing with a tolerance in the order of 1e-6 is probably the way to go.
这篇关于比较 Unity 中的浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!