C++ 實現科學計數法string轉double


用於將形如"+2.449E+2"的科學計數法字符串轉為244.9的浮點型數值

代碼如下, 如有疏漏, 歡迎指正

 1 double sci2db(const std::string &strSci)
 2 {
 3   int    iPower       = 0;  //
 4   double dMntsa       = 0;  //尾數
 5   double dCoefficient = 1;  //系數
 6 
 7   std::string strPower, strMntsa;
 8 
 9   if (std::string::npos == strSci.find("E"))
10   {
11     return atof(strSci.c_str());
12   }
13 
14   strMntsa = strSci.substr(0, strSci.find("E"));
15   strPower = strSci.substr(strSci.find("E") + 1);
16 
17   dMntsa = atof(strMntsa.c_str());
18   iPower = atoi(strPower.c_str());
19 
20   while (iPower != 0)
21   {
22     if (iPower > 0)
23     {
24       dCoefficient *= 10;
25       iPower--;
26     }
27     else
28     {
29       dCoefficient *= 0.1;
30       iPower++;
31     }
32   }
33 
34   return dMntsa * dCoefficient;
35 }

使用intel i5-8265U @ 1.60GHz 1.80GHz, 對字符串"+2.449E+2"轉換1000次用時1200ms左右

如果通過一個'0'~'9'的數表自行實現for循環替換atof, atoi的話, 同樣條件轉換1000次用時1000ms左右, 但是對入參的容錯率很低, atof和atoi函數對入參的容錯率很高

大家如果有興趣可以自己嘗試一下


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM