Off*_*rmo 4 c++ floating-point casting
奇怪,因为它可能看起来,我无法找到如何干净地转换float到int.
这种技术
int int_value = (int)(float_value + 0.5);
Run Code Online (Sandbox Code Playgroud)
触发一个
warning: use of old-style cast
Run Code Online (Sandbox Code Playgroud)
在gcc.
那么,什么是现代风格,简单的方式转换float为int?(我当然接受精度的损失)
正如乔希在评论中指出的那样,+ 0.5并不是很可靠.为了获得额外的安全性,您可以将其结合static_cast使用std::round:
int int_value = static_cast<int>(std::round(float_value));
Run Code Online (Sandbox Code Playgroud)
对于铸造部件,请参阅此优秀文章以获得解释.