比较Unity中的花车 [英] Compare floats in Unity
本文介绍了比较Unity中的花车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从这些输入字段获取值,并检查它们的和是否等于100.02。
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(不等于,你的总和=+总数);
$ b我在控制台中得到不等于你的总和= 100.02登录。
无论如何有任何想法,为什么这可能会发生? / code> 16.6700000762939453125
。
$ b 最近的 float
到 10.02
是 100.01999664306640625
前者本身5次并不等于后者,所以他们不会比较相等。
在这个特定的如果按照1e-6的顺序比较容忍度,那么可能就是这样。
I have 6 InputFields in my scene. Their content type is decimal.
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);
}
I am getting " Not equal. Your sum is = 100.02" in my console log.
Anyways has any idea why this might be happening ?
解决方案 The nearest float
to 16.67
is 16.6700000762939453125
.
The nearest float
to 10.02
is 100.01999664306640625
Adding the former to itself 5 times is not exactly equal to the latter, so they will not compare equal.
In this particular case, comparing with a tolerance in the order of 1e-6 is probably the way to go.
这篇关于比较Unity中的花车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文