在 std::floor 之后转换为 int 是否保证正确的结果?

Does casting to an int after std::floor guarantee the right result?(在 std::floor 之后转换为 int 是否保证正确的结果?)
本文介绍了在 std::floor 之后转换为 int 是否保证正确的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我想要一个带有语法的 floor 函数

I'd like a floor function with the syntax

int floor(double x);

但是 std::floor 返回一个 double.是

but std::floor returns a double. Is

static_cast <int> (std::floor(x));

保证给我正确的整数,或者我可能有一个一对一的问题?它似乎有效,但我想确定.

guaranteed to give me the correct integer, or could I have an off-by-one problem? It seems to work, but I'd like to know for sure.

对于奖励积分,为什么 std::floor 一开始会返回 double ?

For bonus points, why the heck does std::floor return a double in the first place?

推荐答案

double 的范围远大于 32 或 64 位整数的范围,这就是为什么 std::floor 返回一个双重.强制转换为 int 应该没问题,只要它在适当的范围内 - 但请注意 double 不能准确表示所有 64 位整数,因此您也可以结束当您超过 double 的准确性使得两个连续双精度之间的差异大于 1 时,就会出现错误.

The range of double is way greater than the range of 32 or 64 bit integers, which is why std::floor returns a double. Casting to int should be fine so long as it's within the appropriate range - but be aware that a double can't represent all 64 bit integers exactly, so you may also end up with errors when you go beyond the point at which the accuracy of double is such that the difference between two consecutive doubles is greater than 1.

这篇关于在 std::floor 之后转换为 int 是否保证正确的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do compilers treat variable length arrays(编译器如何处理变长数组)
Deduce template argument from std::function call signature(从 std::function 调用签名推导出模板参数)
check if member exists using enable_if(使用 enable_if 检查成员是否存在)
Standard Library Containers with additional optional template parameters?(具有附加可选模板参数的标准库容器?)
Uses of a C++ Arithmetic Promotion Header(C++ 算术提升标头的使用)
Parameter pack must be at the end of the parameter list... When and why?(参数包必须位于参数列表的末尾...何时以及为什么?)