早就听说 float和double内存管理的原因不能直接比较大小。今天,借助unity平台,来看一下 c#中float的比较问题。
1.常数比较和未计算的变量比较
using UnityEngine;
using System.Collections;
public class Main : MonoBehaviour {
float testNum = 1f;
float resultNum = 1f;
// Use this for initialization
void Start () {
Debug.Log(1f == 1f);
Debug.Log(testNum == resultNum);
Debug.Log(testNum == 1f);
Debug.Log(testNum.Equals(resultNum));
Debug.Log(testNum.Equals(1f));
}
// Update is called once per frame
void Update () {
}
}
结果返回5个true
2.比较运算之后的结果
<pre name="code" class="csharp">using UnityEngine;
using System.Collections;
public class Main : MonoBehaviour {
float testNum = 1f;
float resultNum = 1f;
// Use this for initialization
void Start () {
float sum = 0f;
for(int i = 0; i < 10; i++)
{
sum += 0.1f;
}
Debug.Log(sum+" "+(sum == testNum));
Debug.Log(sum+" "+(sum.Equals(testNum)));
Debug.Log(sum+" "+(sum == 1f));
Debug.Log(sum+" "+(sum.Equals(1f)));
}
// Update is called once per frame
void Update () {
}
}
运行之后 发现虽然 sum==1 但是sum!= testNum
所以,float变量的比较(尤其是某一变量经过了计算),要用
Mathf.Abs(testNum - resultNum) < 0.001
当然 0.001是精度,可以根据自己的需求设置
3.float强制转化
using UnityEngine;
using System.Collections;
public class Main : MonoBehaviour {
float testNum = 2f;
// Use this for initialization
void Start () {
Debug.Log(1 / 2);
Debug.Log(1 / testNum);
Debug.Log(1f / testNum);
Debug.Log(1f / 2);
}
// Update is called once per frame
void Update () {
}
}
除第一个外,均为0.5,说明二者只要有一个是float即可。
4.除以0
在unity中可以除以0 大家可以试一下 Debug.Log(1/0); 结果我就不说了。。。。。。哈哈