【发布时间】:2015-11-22 12:34:01
【问题描述】:
我正在使用 Visual Studio 2015 打印两个浮点数:
double d1 = 1.5;
double d2 = 123456.789;
std::cout << "value1: " << d1 << std::endl;
std::cout << "value2: " << d2 << std::endl;
std::cout << "maximum number of significant decimal digits (value1): " << -std::log10(std::nextafter(d1, std::numeric_limits<double>::max()) - d1) << std::endl;
std::cout << "maximum number of significant decimal digits (value2): " << -std::log10(std::nextafter(d2, std::numeric_limits<double>::max()) - d2) << std::endl;
这将打印以下内容:
value1: 1.5
value2: 123457
maximum number of significant decimal digits (value1): 15.6536
maximum number of significant decimal digits (value2): 10.8371
为什么将 123457 打印为值 123456.789?当 std::cout 不使用 std::setprecision() 时,ANSI C++ 规范是否允许显示任何浮点数?
【问题讨论】:
-
" ANSI C++ 规范是否允许在不使用 std::setprecision() 的情况下使用 std::cout 时显示浮点数的任何内容?"是的。
-
@Hermantas,对,我的意思是 std::cout。
-
@Mats,为什么规范在这个主题上如此含糊?如果规范更具体(例如打印带有有效数字的浮点数),它将对开发人员有所帮助。类似 printf("%.16g\n", d).
-
默认精度为 6,和 printf 一样。
-
@Bo,正确的 std::cout.precision() 给出 6。因此规范定义明确。谢谢。
标签: c++