float精度问题

来源:互联网 发布:买域名一年多少钱 编辑:程序博客网 时间:2024/06/10 09:20

<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;
经试验问题得到了解决。

点击打开链接

0 0
原创粉丝点击