我的场景中有 6 个 InputField。它们的内容类型是十进制。
我从这些输入字段中获取值并检查它们的总和是否等于 100.02。我全部输入 16.67。
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”。 无论如何知道为什么会发生这种情况?
最佳答案
你确实有一个浮点问题。
在 unity 中你可以而且应该使用 Mathf.Approximately
,这是他们专门为此目的构建的效用函数
试试这个
if (Mathf.Approximately(total, 100.02f))
{
Debug.Log("It's equal");
}
else
{
Debug.Log(" Not equal. Your sum is = " + total);
}
此外,作为旁注,如果您计划进行任何具有精确数字至关重要的计算,则应使用 Decimals。它是一个稍大的数据结构,因此速度较慢,但它被设计为没有浮点问题。 (或至少精确到 10^28)
对于 99.99% 的情况, float 和 double 就足够了,前提是您正确地比较了它们。
可以在此处找到更深入的解释:Difference between decimal float and double in .net
关于c# - 在 Unity 中比较 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39898301/