2013-05-15 47 views
4

雖然看起來很奇怪,但我找不到如何將float乾淨地轉換爲int如何在現代C++中將float轉換爲int

這種技術

int int_value = (int)(float_value + 0.5); 

觸發

warning: use of old-style cast 
在GCC

那麼,將float轉換爲int的現代風格簡單的方法是什麼? (我接受丟失精度當然)

+2

最現代的方式是'std :: round'。 – chris

+0

int int_value = float_value + .5f;'do?提示:0.5是雙倍。 –

+0

@chris'round'將返回一個浮點數。你可以調用'lround',但是返回一個long,而不是int。哦,現在我看到你只是在談論四捨五入的部分,而不是投到int部分。這會教會我在評論之前閱讀整個問題:-) – Praetorian

回答

4

正如喬希在評論中指出的,+ 0.5不是很可靠。對於額外的安全性,您可以用std::round結合了static_cast像這樣:

int int_value = static_cast<int>(std::round(float_value)); 

對於鑄件,看到this excellent post一個解釋。

+5

由於浮點數學問題,「+ 0.5」是一個令人驚訝的不可靠的方法。請參閱http://blog.frama-c.com/index.php?post/2013/05/02/nearbyintf1。 –

+0

@JoshKelley,好點。編輯。 –

+0

'static_cast'在這裏完全沒有;一旦你完成了'std :: round',你可以忘記它(並且如果流不適合,就會得到未定義的行爲),或者你可以將結果賦給一個'float',並檢查'std :: numeric_limits :: max()'和'std :: numeric_limits :: min'在做任務之前。 ('lexical_cast'是一個非常糟糕的主意,因爲它不起作用。) –

1

嘗試:

int int_value = static_cast<int>(float_value + 0.5); 

FYI:different casts in C++給了有關用C++介紹這4投下了一個很好的解釋。

1

你也可以考慮

int int_value = boost::lexical_cast<int>(float_value); 

的lexical_cast對所有原始類型工作的效益和STL串等。這也意味着你不必做(float_value + 0.5)的東西。

+0

如果中間字符串包含一個小數點,則這將不起作用,並且這可能是浮點數。或者,如果浮動很大。此外,爲了舍入負值,你想減去0。5,所以四捨五入不是那麼容易。 –