用于将形如"+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函数对入参的容错率很高
大家如果有兴趣可以自己尝试一下
原文链接: https://www.cnblogs.com/TssiNG-Z/p/12758850.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/343908
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!