問題描述
我想要一個帶有語法的 floor
函數
I'd like a floor
function with the syntax
int floor(double x);
但是 std::floor
返回一個 double
.是
but std::floor
returns a double
. Is
static_cast <int> (std::floor(x));
保證給我正確的整數,或者我可能有一個一對一的問題?它似乎有效,但我想確定.
guaranteed to give me the correct integer, or could I have an off-by-one problem? It seems to work, but I'd like to know for sure.
對于獎勵積分,為什么 std::floor
一開始會返回 double
?
For bonus points, why the heck does std::floor
return a double
in the first place?
推薦答案
double 的范圍遠大于 32 或 64 位整數的范圍,這就是為什么 std::floor
返回一個雙重
.強制轉換為 int
應該沒問題,只要它在適當的范圍內 - 但請注意 double
不能準確表示所有 64 位整數,因此您也可以結束當您超過 double
的準確性使得兩個連續雙精度之間的差異大于 1 時,就會出現錯誤.
The range of double is way greater than the range of 32 or 64 bit integers, which is why std::floor
returns a double
. Casting to int
should be fine so long as it's within the appropriate range - but be aware that a double
can't represent all 64 bit integers exactly, so you may also end up with errors when you go beyond the point at which the accuracy of double
is such that the difference between two consecutive doubles is greater than 1.
這篇關于在 std::floor 之后轉換為 int 是否保證正確的結果?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!