日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

C++?float轉(zhuǎn)std::string?小數(shù)位數(shù)控制問題_C 語言

作者:Atticus_DY ? 更新時(shí)間: 2022-12-08 編程語言

float轉(zhuǎn)std::string 小數(shù)位數(shù)控制

std::stringstream 方式

?? ?float a = 1122.334455;
?? ?std::stringstream buf;
?? ?buf.precision(2);//覆蓋默認(rèn)精度
?? ?buf.setf(std::ios::fixed);//保留小數(shù)位
?? ?buf << a << "文字";
?? ?std::string str;
?? ?str = buf.str();

sprintf 方式

? ? float a = 1122.334455;
?? ?char* chCode;
?? ?chCode = new(std::nothrow)char[20];
?? ?sprintf(chCode, "%.2lf", a);// .2 是控制輸出精度bai的,兩位小數(shù)
?? ?std::string strCode(chCode);
?? ?delete []chCode;

string轉(zhuǎn)float顯示位數(shù)有誤;cout 的 precision 成員函數(shù)

問題描述

在進(jìn)行string轉(zhuǎn)float過程中,發(fā)現(xiàn)有些數(shù)顯示位數(shù)不同(存在數(shù)精度少了一位的情況,例如:0.1285354 轉(zhuǎn)換后,顯示 0.128535)

數(shù)據(jù)如下:

0.0281864
-0.0635702
0.0457153
0.1285354
-0.0254498
...

問題分析

后了解到 float 只顯示有效位數(shù) 6 位, 而 double 顯示有效位數(shù) 15 位

  • float有效數(shù)字位為6 – 7位,字節(jié)數(shù)為4,指數(shù)長度為8位,小數(shù)長度為23位。取值范圍為 3.4E-38~3.4E+38。
  • double有效數(shù)字位為15 – 16位,字節(jié)數(shù)為8,指數(shù)長度為11位,小數(shù)長度為52位。取值范圍為1.7E-308~1.7E+308。

隨即思考,是不是轉(zhuǎn)換后賦值到了float上,導(dǎo)致精度降低呢?

馬上修改賦值到double類型上,然而任然顯示有誤。

這才想到會不會使 cout 輸出精度的問題,搜索后發(fā)現(xiàn) cout 需要調(diào)用 precision() 成員函數(shù)來設(shè)置顯示精度,而 cout 默認(rèn)精度為6位有效數(shù)字,哈哈真是湊巧,跟 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 設(shè)置浮點(diǎn)數(shù)輸出精度方法

方法一(全局設(shè)置 cout 輸出精度)

#include <iostream>
double tmp = 0.1234567890123456;
cout.precision(16);?? ?//此處設(shè)置后,全局有效;cout浮點(diǎn)數(shù)輸出精度均為16
cout << tmp << endl;

方法二(全局設(shè)置 cout 輸出精度)

#include <iostream>
#include <iomanip>
double tmp = 0.1234567890123456;
cout << setprecision(16) << tmp << endl; //此處設(shè)置后,全局有效;后面cout浮點(diǎn)數(shù)輸出精度均為16
cout << 0.1234567890123456 << endl;?? ?// 0.1234567890123456

原文鏈接:https://blog.csdn.net/Atticus_DingYu/article/details/107064540

欄目分類
最近更新