首页 > 其他分享 >关于浮点数转整数不准确问题

关于浮点数转整数不准确问题

时间:2024-04-07 21:45:03浏览次数:23  
标签:int 浮点数 unsigned 整数 dNUMTmp include 准确

#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>


using namespace std;
int main(int argc, char **argv) 
{
     double dNUM = 1.001;
     double dNUMTmp = dNUM * 1000;
     unsigned int iNUMTmp = (unsigned int)dNUMTmp;
     cout << "dNUM : "<< to_string(dNUM) << endl;
     cout << "dNUMTmp : "<< to_string(dNUMTmp) << endl;
     cout << "iNUMTmp : "<< to_string(iNUMTmp) << endl;
     cout << "dNUMTmp - iNUMTmp : "<< to_string(dNUMTmp - iNUMTmp) << endl;
     cout << "abs(dNUMTmp - iNUMTmp) : "<< to_string(abs(dNUMTmp - iNUMTmp)) << endl;

     if (abs(dNUMTmp - iNUMTmp) != 0.0)
     {
         cout << "dNUMTmp != iNUMTmp" << endl;
     } else 
     {
         cout << "dNUMTmp == iNUMTmp" << endl;
     }
     return 0;
}

实际运行时,会发现转换为整数后,两者实际是不相等的,此时整数为1000,浮点数为1001.。笔者怀疑是由于浮点数转换掉用函数_ftol2导致的。


此时在转换时,向上取整ceil或者四舍五入round即可。

注:浮点数不能用 ==  !=等进行比较,可以在在精度范围内进行比较

相关链接:

https://blog.csdn.net/unknowm/article/details/2906938
https://www.cnblogs.com/ErosLii/p/4437938.html

标签:int,浮点数,unsigned,整数,dNUMTmp,include,准确
From: https://www.cnblogs.com/dtreus2023/p/18119976

相关文章