截断并转换为 ceiled double 的 int

Truncate and casting to int of ceiled double

对双精度值执行 std::ceil 时,该值将四舍五入为整数。所以3.3会变成4.0。可以转换或截断为 int。 'chop off' 逗号后的部分。所以:

int foo = (int)std::ceil(3.3);

乍一看,这会将 4 存储在 foo 中。但是,double 是一个浮点值。所以它可能是 4.0000000013.999999999。后者将被截断为 3。

但实际上我从未见过这种行为发生。我可以安全地假设任何实现都会 return 4 吗?还是只有 IEEE-754 执行此操作。还是我只是运气好?

ceil 在 C++ 中的行为类似于在 C 中的行为,其中标准说

The ceil functions compute the smallest integer value not less than x.

ceil的结果始终是整数的浮点表示;但是,结果在截断时可能会溢出整数类型。

在您的特定情况下,std::ceil(3.3) 必须 正好是 4.0,因为那是 "smallest integer value not less than" 3.3

双精度数的四舍五入(或上限)将始终、始终、始终准确。

对于2^(m+1)以下的浮点数,其中m是尾数位数,所有整数都有精确表示,所以可以精确表示结果。

对于大于 2^(m+1) 的浮点数...它们已经是整数。如果您考虑一下,这是有道理的:没有足够的尾数位来向下延伸到小数点的右边。所以再次 rounding/ceil-ing 是准确的。