C++ float轉(zhuǎn)std::string 小數(shù)位數(shù)控制問題
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
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C++設(shè)置超時時間的簡單實(shí)現(xiàn)方法
這篇文章主要介紹了C++設(shè)置超時時間的簡單實(shí)現(xiàn)方法,涉及系統(tǒng)函數(shù)setsockopt對套接口的操作,具有一定的實(shí)用價值,需要的朋友可以參考下2014-10-10C語言使用鏈表實(shí)現(xiàn)學(xué)生籍貫管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了C語言使用鏈表實(shí)現(xiàn)學(xué)生籍貫管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02C++ LeetCode1775通過最少操作次數(shù)使數(shù)組和相等
這篇文章主要為大家介紹了C++ LeetCode1775通過最少操作次數(shù)使數(shù)組和相等,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12