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

时间:2023-03-07
本文介绍了在 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 是否保证正确的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:剪辑数字的最有效/优雅的方法? 下一篇:矩形与矩形相交的面积

相关文章