我正在尝试将一个大的 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 double precision ,这意味着它具有 53 位尾数(“值”)精度、11 位指数精度和 1 位符号位。
数字 123456789123456789123456789123456789 需要超过 53 位来表示,这意味着典型的 double
不可能准确地表示它。如果您想要如此大的数字并具有完美的精度,则需要使用某种“大数字”库。
有关浮点格式及其不准确性的更多信息,您可以阅读 What Every Programmer Should Know About Floating-Point Arithmetic。
关于c++ - 在 C++ 中使用 float ( double )丢失精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48148235/