This question already has an answer here:
这个问题已经有了答案:
- Why do round() and ceil() not return an integer? 2 answers
- 为什么round()和ceil()不返回整数?2答案
Just now I stumbled upon the fact, that the C++ function floor
returns the same type you pass to it, be it float
, double
or such.
刚才我无意中发现了一个事实,即c++函数层返回的类型与您传递给它的类型相同,可以是float类型,double类型或此类类型。
According to this reference, the function returns a down rounded integral value. Why isn't this an integer?
根据此引用,函数返回一个向下的整数整数值。为什么这不是一个整数?
1 个解决方案
#1
47
Because an integral type can't necessarily hold the same integral values as a 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;
}
outputs (on my x86_64 architecture)
输出(在我的x86_64架构上)
3.40282e+38
-9223372036854775808
Additionally, floating-point values can hold NaN, +Inf, and -Inf, all of which are preserved by a floor()
operation. None of these values can be represented with an integral type.
此外,浮点值可以容纳NaN、+Inf和-Inf,所有这些都由一个层()操作保存。这些值都不能用整数类型表示。
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
#1
47
Because an integral type can't necessarily hold the same integral values as a 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;
}
outputs (on my x86_64 architecture)
输出(在我的x86_64架构上)
3.40282e+38
-9223372036854775808
Additionally, floating-point values can hold NaN, +Inf, and -Inf, all of which are preserved by a floor()
operation. None of these values can be represented with an integral type.
此外,浮点值可以容纳NaN、+Inf和-Inf,所有这些都由一个层()操作保存。这些值都不能用整数类型表示。
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