如何在现代c++中将浮点数转换为整型
How to convert a float to an int in modern C++
看起来很奇怪,我找不到如何清晰地将float
转换为int
。
这个技术
int int_value = (int)(float_value + 0.5);
触发
warning: use of old-style cast
在gcc。那么,将float
转换为int
的现代风格的简单方法是什么?(我当然接受精度的损失)
正如Josh在评论中指出的那样,+ 0.5
不是很可靠。为了获得额外的安全性,您可以将static_cast
与std::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)的东西
相关文章:
- 将浮点数转换为无符号字符数组并打印出来
- 如何将浮点数转换为uint8_t?
- 为什么C++在将浮点数转换为字符时没有显示缩小转换错误?
- 将浮点数转换为字符串时如何加快此代码的速度?
- C/C++ - 将浮点数转换为字节数组,以便字节保持排序
- 精确且无公差地将浮点数转换为字符串
- 错误:请求从 std::chrono::time_point 浮点数转换为非标量类型长整型
- 将浮点数转换为 LPCTSTR 转换
- 无法在初始化时将浮点数转换为浮点数
- 将浮点数转换为 int,带和不带强制转换
- 将浮点数转换为 int,或将 int 强制转换为浮点数
- 将浮点数转换为字符串,并指定精度和十进制数字数?
- 将范围有限的浮点数转换为无符号的整数,以保持排序顺序和精度
- 如何将浮点数转换为保留位值的整数
- 将浮点数转换为 LPCWSTR
- 正在将浮点数转换为整数定义的行为
- 将浮点数转换为整数时如何舍入
- 将浮点数转换为浮点数*
- 无需任何库函数即可将浮点数转换为字符串的有效方法
- 将浮点数转换为 4 uint8_t