簡體   English   中英

以下轉換整數從哪個數字開始->雙精度->整數無效?

[英]From what number the following conversion integer -> double -> integer is not valid?

假設我的計算機使用IEEE 754浮點編碼,我想知道以下函數返回false的最小數字是多少:

constexpr bool test(const unsigned long long int x)
{
    return static_cast<unsigned long long int>(static_cast<double>(x)) == x;
}

IEEE-754中double精度數的尾數為53位(52位和1位隱藏,非常技術性)。 這意味着,如果x中的最高位高於第52位,而某些較低位為非零,則比較將失敗。

您可以通過編寫一段代碼來找出答案:

unsigned long long x = 0x1;

while(x > 0)
{
   x <<= 1ULL;
   if (!test(x+1))
   {
      cout << "x=" << hex << x << endl;
      break;

   }
}

編輯:在實際測試后修復了一點代碼。

它確實按預期打印x=20000000000000

或者,如果要使用<limits> ,則可以使用以下方法實現相同的結果:

numeric_limits<double> n;
cout << "digits=" << dec << n.digits << " -> " << hex << (1ULL << n.digits) << endl;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM