尽管看起来很奇怪,但我找不到如何将 float
干净地转换为 int
。
这个技巧
int int_value = (int)(float_value + 0.5);
触发一个
warning: use of old-style cast
在海合会中。
那么,将 float
转换为 int
的现代风格的简单方法是什么? (我当然接受精度的损失)
最佳答案
正如 Josh 在评论中指出的那样,+ 0.5
不是很可靠。为了额外的安全,您可以像这样将 static_cast
与 std::round
结合起来:
int int_value = static_cast<int>(std::round(float_value));
铸件见this excellent post寻求解释。
关于c++ - 如何在现代 C++ 中将 float 转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16570740/