刚才我偶然发现了一个事实,即C++函数floor
返回您传递给它的同类型,无论是float
,double
还是这样.
根据该引用,该函数返回向下舍入的整数值.为什么这不是整数?
Lil*_*ard 50
因为积分类型不一定能保持与a float
或者相同的积分值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;
}
Run Code Online (Sandbox Code Playgroud)
输出(在我的x86_64架构上)
3.40282e+38
-9223372036854775808
Run Code Online (Sandbox Code Playgroud)
此外,浮点值可以保存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;
}
Run Code Online (Sandbox Code Playgroud)
输出
nan
inf
-inf
Run Code Online (Sandbox Code Playgroud)