为什么我在每个 std::nexttowards 函数调用上都得到相同的结果
Why am I getting the same results on every std::nexttoward function call
为什么下面的代码在每次std::nexttoward
函数调用时都返回相同的数字?
#include <cmath>
#include <iostream>
#include <limits>
int main()
{
std::cout.precision(std::numeric_limits<double>::max_digits10);
std::cout.setf(std::ios::fixed);
auto foo = 0.00000000000011134;
std::cout << foo << std::endl;
for (int i = 0; i < 100; ++i)
{
foo = std::nexttoward(foo, 1.0);
std::cout << foo << std::endl;
}
}
http://coliru.stacked-crooked.com/a/551b6e2b867b2f3b
这里提到的任何标志都没有设置(FE_OVERFLOW, FE_UNDERFLOW и FE_INEXACT) 。
这是因为浮点格式通常面向保留一定数量的有效数字。
std::cout.setf(std::ios::fixed);
使用具有较小数值的std::ios::fixed
格式会强制格式化输出插入一堆不重要的"前导"零(在小数点之后)。这就是您在测试程序输出中真正看到的内容。这是以截断实际有效数字为代价的,当I/O库必须在固定precision()
之后切断所有内容时。
删除std::ios::fixed
格式标志(并保持precision()
)后,输出变为您所期望的(使用 gcc 7.2.1 测试了自己,并在 Colliru 上重现):
1.1134e-13
1.1134000000000001e-13
1.1134000000000002e-13
1.1134000000000003e-13
1.1134000000000005e-13
1.1134000000000006e-13
1.1134000000000007e-13
1.1134000000000008e-13
1.113400000000001e-13
1.1134000000000011e-13
1.1134000000000012e-13
。等
将小数点向左移动十三位(这就是e-13
所说的),然后亲自看看在std::ios::fixed
砍掉指定位数后的所有内容后会发生什么。
相关文章:
- 函数调用中参数的顺序重要吗
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 变量没有改变?通过向量的函数调用
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 我知道函数调用中存在歧义.有没有办法调用foo()函数
- 模板函数调用
- 获取从C++中同一类中的构造函数调用的方法返回的值
- 析构函数调用
- 从返回 std::optional of std::vector 的函数中获取结果到调用方
- C ++ DLL导入:函数调用返回错误的结果
- GCC 9.1 返回 void& 作为显式析构函数调用的结果类型。这是一个错误吗?
- 为什么我在每个 std::nexttowards 函数调用上都得到相同的结果
- 对于相同的输入参数,多个函数调用返回不同的结果
- 存储一个函数的迭代结果,并在被另一个函数调用时使用它们
- 如何解释模板函数调用的 gcov 结果
- 使用函数调用结果在C++03中初始化多个成员
- C函数调用产生的结果与C++函数调用不同
- 如何自动键入函数调用的结果
- 我可以用函数调用的结果初始化一个全局变量吗