[英]Is there a floating point literal suffix in C++ to make a number double precision?
[英]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.