c ++ float to bool转换 [英] c++ float to bool conversion
问题描述
我在看一些第三方代码,我不确定一行是做什么。我不能发布确切的代码,但它是沿着这样的线:
I'm looking at some 3rd party code and am unsure exactly what one line is doing. I can't post the exact code but it's along the lines of:
bool function(float x)
{
float f = doCalculation(x);
return x > 0 ? f : std::numeric_limits<float>::infinity();
}
这显然会引起编译器关于转换float-> bool的警告,实际行为是什么? Visual C ++如何将浮动转换为bools?至少我应该能够替换那个讨厌的无限...
This obviously throws a warning from the compiler about converting float->bool, but what will the actual behaviour be? How does Visual C++ convert floats to bools? At the very least I should be able to replace that nasty infinity...
推荐答案
我认为这是一个错误。该函数应该返回一个浮点数。这对我来说似乎符合逻辑。
I think it is a mistake. That function should return a float. This seem logical to me.
浮动到bool的转换与float!= 0相同。但是,严格比较两个浮点并不总是如你所期望的,由于精度。
The conversion float to bool is the same as float != 0. However, strict comparing two floating points is not always as you'd expect, due to precision.
这篇关于c ++ float to bool转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!