C++数据精度问题(对浮点数保存指定位小数)分享

—-想了解C++数据精度问题(对浮点数保存指定位小数)分享的全部内容且更多的C语言教程关注<计算机技术网(www.ctvol.com)!!>

1、背景
对浮点数保存指定位小数。比如, 1.123456. 要保存1位小数,,调用方法后, 保存的结果为: 1.1。 再比如,1.98765, 保存2位小数的结果为: 2.00.

2、 解决方案
A、添加头文件

  #include <sstream>   #include <iomanip> 

B、添加命名空间

  using namespace std; 

C、添加函数

  /* 函数名:round   /* 函数功能:数据精度计算函数   /* 函数参数:float src:待求精度数   int bits:精度(0表示保留小数点后0位小数,1表示保留1位小数,2:表示保留2位小数)   /* 函数返回值:精度求取结果   /* Author: Lee   /************************************************************************/   float round(float src, int bits); 

函数实现

  float CDemo1Dlg::round(float src, int bits)   {     stringstream ss;     ss << fixed << setprecision(bits) << f;     ss >> f;        return f;      } 

D、调用方式

  CString str2 = L"99.054";   float f2 = (float)_wtof(str2);   f2 *= 10;   f2 = this->round(f2, 2); 

 E 、注意
比如, 1.05, double在计算机中表示为 1.0499999997, float表示为1.0500000003, 但其实际都是与1.05相等的。
round方方式对处理的位数为5的情况有例外,比如: 1.05, 处理的结果 可能为1.0499999997。 这里写的是float, 你可以换做其他的类型。自己多测几次就明白了

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/488405.html

(1)
上一篇 2020年11月12日
下一篇 2020年11月12日

精彩推荐