如何在现代c++中将浮点数转换为整型

How to convert a float to an int in modern C++

本文关键字:浮点数 转换 整型 c++      更新时间:2023-10-16

看起来很奇怪,我找不到如何清晰地将float转换为int

这个技术

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

触发

warning: use of old-style cast
在gcc。

那么,将float转换为int的现代风格的简单方法是什么?(我当然接受精度的损失)

正如Josh在评论中指出的那样,+ 0.5不是很可靠。为了获得额外的安全性,您可以将static_caststd::round组合使用,如下所示:

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

关于选角部分,请参阅这篇优秀的文章。

try:

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

仅供参考:c++中的不同类型转换对c++中引入的4种类型转换给出了很好的解释。

你也可以考虑

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

lexical_cast具有适用于所有基本类型和STL字符串等的优点。这也意味着你不必做(float_value + 0.5)的东西