在std :: floor之后转换为int是否保证正确的结果? [英] Does casting to an int after std::floor guarantee the right result?

查看:643
本文介绍了在std :: floor之后转换为int是否保证正确的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个 floor 函数,语法为

I'd like a floor function with the syntax

int floor(double x);

std :: floor code> 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.

对于奖励积分,为什么heck会 std :: floor

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

推荐答案

double的范围大于32或64位整数的范围,这就是为什么 std :: floor 返回 double 。转换到 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是否保证正确的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆