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

學無先后,達者為師

網站首頁 編程語言 正文

C++?float轉std::string?小數位數控制問題_C 語言

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

float轉std::string 小數位數控制

std::stringstream 方式

?? ?float a = 1122.334455;
?? ?std::stringstream buf;
?? ?buf.precision(2);//覆蓋默認精度
?? ?buf.setf(std::ios::fixed);//保留小數位
?? ?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的,兩位小數
?? ?std::string strCode(chCode);
?? ?delete []chCode;

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

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

欄目分類
最近更新