float精度问题

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">最近写一小程序,出现了一个莫名的问题,今天捣鼓了一天才发现是float的精度问题</span>
<span style="font-family:Arial, Helvetica, sans-serif;"><span style="background-color: rgb(255, 255, 255);">原来是这么写的:</span></span>
<span style="font-family:Arial, Helvetica, sans-serif;"><span style="background-color: rgb(255, 255, 255);"></span></span><pre name="code" class="cpp"><span style="white-space:pre">	</span>int Index = -1;
	for(int i=0; i<m_colorband.colors.size(); i++)
	{		
		if ( (anchors.at(m_selectAnchorIndex).m_anchorPos ) == (m_colorband.m_colorPoss.at(i) ) )
			Index = i;
	}
	m_colorband.m_selectIndex = Index;
发现判断不准,百思不得其解,后来发现 anchors.at(m_selectAnchorIndex).m_anchorPos与 m_colorband.m_colorPoss.at(i)仅仅因为极小的误差而被判断为不相等,才知道float的精度是6~7位有效数字,而我定义的这两个变量的取值在0.0~100.0之间,也就是说至少小数点后4位是精确的,然后我将代码改成:

 

<span style="white-space:pre">	</span>int Index = -1;
	for(int i=0; i<m_colorband.colors.size(); i++)
	{
		//0.0-100.0之间的float,小数点后四位是精确的
		if ( (int)(anchors.at(m_selectAnchorIndex).m_anchorPos * 10000) == (int)(m_colorband.m_colorPoss.at(i) * 10000) )
			Index = i;
	}
	m_colorband.m_selectIndex = Index;
经试验问题得到了解决。

点击打开链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值