float问题
来源:互联网 发布:沙发什么意思网络用语 编辑:程序博客网 时间:2024/05/21 18:36
早就听说 float和double内存管理的原因不能直接比较大小。今天,借助unity平台,来看一下 c#中float的比较问题。
1.常数比较和未计算的变量比较
using UnityEngine;using System.Collections;public class Main : MonoBehaviour {float testNum = 1f;float resultNum = 1f;// Use this for initializationvoid 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 framevoid 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 initializationvoid 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 framevoid 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 initializationvoid Start () {Debug.Log(1 / 2);Debug.Log(1 / testNum);Debug.Log(1f / testNum);Debug.Log(1f / 2);}// Update is called once per framevoid Update () {}}
除第一个外,均为0.5,说明二者只要有一个是float即可。
4.除以0
在unity中可以除以0 大家可以试一下 Debug.Log(1/0); 结果我就不说了。。。。。。哈哈
0 0
- float问题
- float问题
- double,float精度问题
- ie8 css float问题
- css float问题
- mysql float 的问题
- 解决“float塌陷”问题
- css float闭合问题
- float/double 存储问题
- float的精度问题
- float精度问题
- float精度问题
- float的存储问题
- float布局问题汇总
- double,float精度问题
- float double 精度问题
- java float问题
- float精度问题
- redis 的两种持久化方式及原理
- 清除系统垃圾
- kill运行程序命令
- 微信VS支付宝服务窗 互联网大佬的O2O争夺战
- 如何卸载软件
- float问题
- MySQL5.0版本的安装图解【转】
- 第十四周 项目三:多科成绩单(3.3)
- [c++,algorithm]3_fpTree
- js 数字校验
- c# 代码生成6个checkbox 并初始化已知的一个数组到checkboxtext内
- 如何成为顶尖WordPress开发者
- 人品计算器
- 第14周项目增加string name[]输出分数的最高,最低,平均分,总分