刚才我偶然发现了一个事实,即 C++ 函数floor
返回与您传递给它的类型相同的类型,无论是float
, double
或诸如此类。
根据这个参考 http://www.cplusplus.com/reference/cmath/floor/,该函数返回一个向下舍入的整数值。为什么这不是一个整数?
因为整型不一定能保存与整型相同的整型值float
or double
.
int main(int argc, char *argv[]) {
std::cout << floor(std::numeric_limits<float>::max()) << std::endl;
std::cout << static_cast<long>(floor(std::numeric_limits<float>::max())) << ::endl;
}
输出(在我的 x86_64 架构上)
3.40282e+38
-9223372036854775808
此外,浮点值可以保存 NaN、+Inf 和 -Inf,所有这些都由floor()
手术。这些值都不能用整数类型表示。
int main(int argc, char *argv[]) {
std::cout << floor(std::numeric_limits<float>::quiet_NaN()) << std::endl;
std::cout << floor(std::numeric_limits<float>::infinity()) << std::endl;
std::cout << floor(-std::numeric_limits<float>::infinity()) << std::endl;
}
outputs
nan
inf
-inf
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)