簡體   English   中英

在C ++中使用浮點數(double)失去精度

[英]Losing precision with floating point numbers (double) in c++

我正在嘗試將一個大的double值分配給一個變量,並將其打印在控制台上。 我輸入的數字與輸出中顯示的數字不同。 是否可以正確分配和輸出double精度值而不損失精度? 這是C ++代碼:

#include <iostream>
#include <limits>

int main( int argc, char *argv[] ) {

    // turn off scientific notation on floating point numbers
    std::cout << std::fixed << std::setprecision( 3 );

    // maximum double value on my machine
    std::cout << std::numeric_limits<double>::max() << std::endl;

    // string representation of the double value I want to get
    std::cout << "123456789123456789123456789123456789.01" << std::endl;

    // value I supplied        
    double d = 123456789123456789123456789123456789.01;

    // it's printing 123456789123456784102659645885120512.000 instead of 123456789123456789123456789123456789.01
    std::cout << d << std::endl;

    return EXIT_SUCCESS;
}

能否請您幫助我理解問題。

C ++內置浮點類型的精度是有限的。 double通常實現為IEEE-754雙精度 ,這意味着它具有53位的尾數(“值”)精度,11位的指數精度和1個符號位。

數字123456789123456789123456789123456789需要超過53位的方式來表示,這意味着典型的double可能無法准確地表示它。 如果您想要如此精確的大數,則需要使用某種“大數”庫。

有關浮點格式及其不准確性的更多信息,您可以閱讀每個程序員應該了解的有關浮點算法的知識

暫無
暫無

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

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