eld*_*jon 1 c++ floating-point precision double
我正在尝试为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;
}
Run Code Online (Sandbox Code Playgroud)
你能帮我理解这个问题吗?
C++ 内置浮点类型的精度是有限的。double通常实现为IEEE-754 double precision,这意味着它具有 53 位尾数(“值”)精度、11 位指数精度和 1 个符号位。
数字 123456789123456789123456789123456789 需要超过 53 位来表示,这意味着一个典型的double不可能准确地表示它。如果您想要具有完美精度的如此大的数字,则需要使用某种“大数字”库。
有关浮点格式及其不准确性的更多信息,您可以阅读每个程序员应该了解的关于浮点运算的知识。
| 归档时间: |
|
| 查看次数: |
1349 次 |
| 最近记录: |