• string转float显示位数有误;cout 的 precision 成员函数


    string转float显示位数有误;cout 的 precision 成员函数

    问题描述:

    在进行string转float过程中,发现有些数显示位数不同(存在数精度少了一位的情况,例如:0.1285354 转换后,显示 0.128535)
    数据如下图:

    0.0281864
    -0.0635702
    0.0457153
    0.1285354
    -0.0254498
    ...
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    问题分析:

    后了解到 float 只显示有效位数 6 位, 而 double 显示有效位数 15 位

    float有效数字位为6 – 7位,字节数为4,指数长度为8位,小数长度为23位。取值范围为 3.4E-38~3.4E+38。
    double有效数字位为15 – 16位,字节数为8,指数长度为11位,小数长度为52位。取值范围为1.7E-308~1.7E+308。

    随即思考,是不是转换后赋值到了float上,导致精度降低呢?

    马上修改赋值到double类型上,然而任然显示有误。

    这才想到会不会使 cout 输出精度的问题,搜索后发现 cout 需要调用 precision() 成员函数来设置显示精度,而 cout 默认精度为6位有效数字,哈哈真是凑巧,跟 float 精度一样。

    修改后代码如下:

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main(int argc, char *argv[]) {
    	const string tmp_str = "0.1285354";
    	float tmp_f = 0;
    	double tmp = 0;
    	cout.precision(16);
    	cout << sizeof(tmp_f) << "--" << sizeof(tmp) << endl;
    	cout << stof(tmp_str) << endl;
    	cout << stod(tmp_str) << endl;
    	cout << stold(tmp_str) << endl;
    	cout << strtod(tmp_str.c_str(), NULL) << endl;
    	cout << atof(tmp_str.c_str()) << endl;
    	tmp = 0.1234567890123456;
    	cout << tmp << endl;
    	return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    程序输出

    nvidia@nx:~/pengjing/cuda$ ./location 
    4--8
    0.1285354048013687
    0.1285354
    0.1285354
    0.1285354
    0.1285354
    0.1234567890123456
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    cout 设置浮点数输出精度方法
    方法一(全局设置 cout 输出精度)

    #include 
    double tmp = 0.1234567890123456;
    cout.precision(16);	//此处设置后,全局有效;cout浮点数输出精度均为16
    cout << tmp << endl;
    
    • 1
    • 2
    • 3
    • 4

    方法二(全局设置 cout 输出精度)

    #include 
    #include 
    double tmp = 0.1234567890123456;
    cout << setprecision(16) << tmp << endl; //此处设置后,全局有效;后面cout浮点数输出精度均为16
    cout << 0.1234567890123456 << endl;	// 0.1234567890123456
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    图像处理中几何畸变校正,图像纠正的方法有哪些
    python sklearn 多输出回归
    我的创作纪念日
    重入锁和读写锁
    Mac中Git如何忽略.DS_Store文件
    SVD求解两个点集之间的刚体运动,即旋转矩阵和平移向量。
    嵌入式Linux学习(1)——经典CAN介绍(上)
    C++11:右值和右值引用
    P1396 营救-最短路dijkstra和最小生成树kruskal+并查集
    onPageNotFound踩坑
  • 原文地址:https://blog.csdn.net/ReturningProdigal/article/details/126279407