55.3 and want 55
55.6 and want 56
81.1 and want 81
etc.
我一直在嘗試使用round()
功能,但它似乎一直給我的最高值,爲所有小數位。
55.3 and want 55
55.6 and want 56
81.1 and want 81
etc.
我一直在嘗試使用round()
功能,但它似乎一直給我的最高值,爲所有小數位。
在過去的日子裏,我們曾經說過int the_int = (int)(some_double + 0.5);
(顯然要小心,如果你正在處理負值)。
我還是這麼說。 – nicomp
爲什麼'round()'不起作用? – juanchopanza
@juanchopanza否 - 'round()'應該工作。我認爲它曾經是爲了避免引入-lm,但我可能是錯的 - 也許有人認爲'round()' – John3136
了一大半增加的幅度和截斷:
int round_up_or_down(double x)
{
return x > 0 ? x + 0.5 : x - 0.5;
}
此分配實際間隔均勻:
[-1.5, -0.5) => -1
[-0.5, +0.5) => 0
[+0.5, +1.5) -> +1
[Demo](https://ideone.com/Ae0xVj) –
但是round()有什麼問題? – juanchopanza
@juanchopanza:沒有什麼,'round'很好 - 它與這個公式有着不同的對稱性,儘管('round'有大約0的反射對稱性,我的平移對稱性)。 –
OP沒有發佈失敗的代碼。某些OP編碼不正確。
使用round()
是轉換爲int
前一個double
圓的正確的方法。當然它必須在範圍內。
#include <math.h>
#include <assert.h>
int round_to_int(double x) {
x = round(x);
assert(x >= INT_MIN);
assert(x < (INT_MAX/2 + 1)*2.0);
return (int) x;
}
有關assert()
s的詳細信息,請參閱How to test for lossless double/integer conversion?。
爲什麼不使用(int)(x + 0.5);
?
1)負數不合格。
2)double
只能比0.5
小,因爲x + 0.5
可以舍入爲1.0
。
3)當int
精度超過double
,值,其中至少顯著位爲0.5或1.0,x+0.5
可以輪到下一個整數。
4)沒有經驗,沒有範圍檢查。
請參閱http://www.tutorialspoint.com/c_standard_library/c_function_floor.htm –
「它似乎不斷給我所有小數位的最高值」 - 您是什麼意思? – Amadan
我將值存儲在float x變量中,當我執行round(x)時,它只會給我所有下一個最高的int – johnnysparks13