尽管看起来很奇怪,但我找不到如何干净地转换float
to an int
.
这种技术
int int_value = (int)(float_value + 0.5);
触发一个
warning: use of old-style cast
in gcc.
那么,什么是现代风格、简单的方法来转换float
to an int
? (我当然接受精度的损失)
正如乔希在评论中指出的那样,+ 0.5
不太可靠。为了额外的安全性,您可以结合static_cast
with std::round
像这样:
int int_value = static_cast<int>(std::round(float_value));
对于铸造部分,请参见这篇优秀的文章以获得解释。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)