2015-07-21 68 views
-5

這是哪個函數的最短形式(不改變這個名字)?四捨五入浮點數的最短函數C++

int NearestInteger(float N) 
{ 
    return round(N); 
} 
+3

你有沒有聽說過Google? –

+0

我什麼都沒發現! –

+1

@Vasiu:你的要求與答案中的功能有什麼不同嗎?(這裏是http://stackoverflow.com/questions/485525/round-for-float-in-c?rq=1)? –

回答

1

如果你沒有C++ 11,你可以這樣做:

int NearestInteger(float N) { 
    return int(floor(N + 0.5f)); 
} 

然而,它可能對大型浮標不正確工作。首先,如果您的號碼不適合int,任何垃圾都可以退回。其次,它可能會返回大於2^24的錯誤結果,因爲not each integer is exactly representable in single precision float number

+1

Exceeded *「如果在目標類型中截斷的值不能爲 ,則行爲未定義。」*每4.9/1'[conv.fpint]'。 –

+0

@TonyD是的,你是對的。來電者不得不擔心溢出。 – stgatilov