c# - 在 Unity 中比较 float

标签 c# unity3d floating-point

我的场景中有 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/

相关文章:

c# - 如何在 ASP.NET Core MVC 中启用跨源请求 (CORS)

unity3d - Unity3D 中的斜面 3d 文本

java - 通过 Android 应用程序下载 Unity .obb 内容

c# - 如何播放动态加载的声音

c++ - matlab 和 c++ 的精度差异

c++ - double,float,{0.0},{0.0f},有什么大不了的?

iphone - 如何在 Swift 4 中打印 float 后的 5 位数字,有没有最短的方法?

c# - 代码契约(Contract),如果 X < Y 且 Y = Z+1 为什么 X < Z+1 未被证明

c# - ServiceStack Redis如何实现分页

c# - 结构图和 Aspnet.Identity UserManager 静态类问题