[英]Why floating point conversion not working?
為什么最小正浮點數的浮點轉換失敗?
#include <iostream>
#include <vector>
int main(){
std::vector<std::string> testStrings;
float fmax = std::numeric_limits<float>::max(); // maximum value
float fmin = std::numeric_limits<float>::min(); // maximum value
std::cout<<fmax<<std::endl;
std::cout<<fmin<<std::endl;
float result=0;
bool status=false;
//below test cases must pass
testStrings.push_back("10");
testStrings.push_back("+10");
testStrings.push_back(" 10 ");
testStrings.push_back("10.253165");
testStrings.push_back("10.253165E12");
testStrings.push_back("11111111111111111111111");
testStrings.push_back("2e-123546132222");
testStrings.push_back("3.40282e+38");
testStrings.push_back("3.40284e+38");
testStrings.push_back("1.17549e-38"); // This test case is throwing out of range exception
for(std::string temp:testStrings)
{
std::stof(temp);
}
}
我正在使用 std::stof 方法進行轉換。
該程序沒有使用足夠的數字來表示具有足夠精度的最小正常float
。
IEEE-754 binary32 中的最小正正態數為 2 -126 ,即 1.1754943508222875079687365372222456778186655567720875215087517062784172594547271728515625•10^ -38 。 但是,這不是問題中的程序傳遞給strtod
的數字。 相反,它只使用了六個有效數字,“1.17549e-38”。 1.17549•10 -38小於 2 -126 ,它比它小很多,以至於將其轉換為float
(使用 IEEE-754 binary32 格式)會產生一個小於 2 -126的數字。 實際產生的數字是 2 −126 − 31•2 −149 。
因此,嘗試使用strtof
將“1.17549e-38”從十進制轉換為浮點會產生范圍錯誤,因為它確實超出范圍(超出正常范圍;該值是可表示的,但 C++ 標准允許超出范圍錯誤導致低於正常范圍)。
教訓:不要只使用六位數。 再使用三個數字“1.17549435e-38”就足以使轉換結果為 2 -126 ,並且不會產生范圍錯誤。 通常,使用九個有效十進制數字就足以將任何 IEEE-754 binary32 格式轉換為十進制並返回將產生原始數字。 (這個值,九,由std::numeric_limits<float>::max_digits10
。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.