c++ - 带 float 的 std::cout

标签 c++

我正在使用 visual studio 2015 打印两个 float :

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::setprecision() 的情况下使用 std::cout 时,ANSI C++ 规范是否允许显示任何 float ?

最佳答案

四舍五入是因为 C++ 标准,可以通过编写看到 std::cout<<std::cout.precision();

输出屏幕将显示 6这表明 std::cout 将打印的默认有效数字位数声明是6 .这就是它自动将 float 四舍五入为 6 位数字的原因。

关于c++ - 带 float 的 std::cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33854825/

相关文章:

c++ - 将虚函数放入一个族中

c++ - 碰撞检测没有得到碰撞

c++ - 为什么即使我设置了它的 repeat = false,定时器也能工作这么多次?

c++ - QScrollArea 在 MacOS X 上的透明背景

c++ - 这两个声明有什么区别?

c++ - 将文件映射到 RAM 的最佳方法?

c++ - windows上 Windows 系统win32框架的替代品

c++ - OpenCV 为键盘事件设置回调

c++ - 从 C++ 中的行中读取单词

c++ - 在Boost中解析RFC3339/ISO 8601时间戳