虽然看起来很奇怪,但我找不到如何将 float
清晰地转换为 int
。
这种技术
int int_value = (int)(float_value + 0.5);
触发一个事件。
warning: use of old-style cast
在GCC中,如何以现代化、简单的方式将float
转换为int
?(当然会有精度损失)
虽然看起来很奇怪,但我找不到如何将 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));
涉及到转换部分,请参考这篇优秀的文章进行了解。
static_cast
在这里完全没有作用;一旦你完成了 std::round
,你可以忘记它(如果流不适合,将得到未定义的行为),或者你可以将结果分配给一个 float
,并在执行赋值之前检查其是否大于 std::numeric_limits<int>::max()
和小于 std::numeric_limits<int>::min()
。(lexical_cast
是非常糟糕的想法,因为它不起作用。) - James Kanzeint int_value = boost::lexical_cast<int>(float_value);
lexical_cast有一个好处,就是适用于所有基本类型、STL字符串等。这也意味着您不必执行(float_value + 0.5)之类的操作。
std::round
。 - chrisint int_value = float_value + .5f;
这行代码是做什么的?提示:0.5 是一个 double 类型。 - Aki Suihkonenround
会返回一个浮点数。你可以调用lround
,但它返回的是long而不是int。哦,现在我明白了,你只是在谈论四舍五入部分,而不是强制转换为int部分。这将教训我在评论之前阅读整个问题:-) - Praetorianlround
的存在。long
和int
大小相同的可能性很大。 - chris