c++ - 如何在现代 C++ 中将 float 转换为 int

标签 c++ casting floating-point

尽管看起来很奇怪,但我找不到如何将 float 干净地转换为 int

这个技巧

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

触发一个

warning: use of old-style cast

在海合会中。

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

最佳答案

正如 Josh 在评论中指出的那样,+ 0.5 不是很可靠。为了额外的安全,您可以像这样将 static_caststd::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/

相关文章:

c++ - 在 C++ 中为抽象类模板创建接口(interface)

c++ - 如何修复 “Undefined symbols for architecture x86_64:” C++编译器错误?

c++ - 作为 std::map 成员的不完整类型

java.lang.ClassCastException : ish. message.Message 无法转换为 android.app.Application

c# - 浮点精度

c++ - 映射或设置具有透明比较器和异构意义上的非唯一元素

c# - 如何在 C# 中将 UIntPtr 对象转换为 IntPtr?

c# - 将字符串转换为字符串的泛型类型

Swift float 乘法错误

java - 将 Java float 转换为 C