为什么floor不返回整数?
刚才我偶然发现了这样一个事实:C ++函数floor
返回了你传递给它的相同类型,无论是float
, double
还是等等。
根据该引用 ,该函数返回向下舍入的整数值。 为什么这不是整数?
因为整数类型不一定能保持与float
或double
相同的整数值。
int main(int argc, char *argv[]) { std::cout << floor(std::numeric_limits::max()) << std::endl; std::cout << static_cast(floor(std::numeric_limits::max())) << ::endl; }
输出(在我的x86_64架构上)
3.40282e+38 -9223372036854775808
此外,浮点值可以保存NaN,+ Inf和-Inf,所有这些都由floor()
操作保留。 这些值都不能用整数类型表示。
int main(int argc, char *argv[]) { std::cout << floor(std::numeric_limits::quiet_NaN()) << std::endl; std::cout << floor(std::numeric_limits ::infinity()) << std::endl; std::cout << floor(-std::numeric_limits ::infinity()) << std::endl; }
输出
nan inf -inf