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

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

问题描述:

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

0.0281864
-0.0635702
0.0457153
0.1285354
-0.0254498
...

问题分析:

后了解到 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 <iostream>
#include <string>
#include <string.h>
#include <stdlib.h>

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;
}

程序输出

nvidia@nx:~/pengjing/cuda$ ./location 
4--8
0.1285354048013687
0.1285354
0.1285354
0.1285354
0.1285354
0.1234567890123456

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

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

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

#include <iostream>
#include <iomanip>
double tmp = 0.1234567890123456;
cout << setprecision(16) << tmp << endl; //此处设置后,全局有效;后面cout浮点数输出精度均为16
cout << 0.1234567890123456 << endl;	// 0.1234567890123456
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值