这是测试程序:
void testFunc()
{
double maxValue = DBL_MAX;
double slope = std::numeric_limits<double>::quiet_NaN();
std::cout << "slope is " << slope << std::endl;
std::cout << "maxThreshold is " << maxValue << std::endl;
std::cout << "the_min is " << std::min( slope, maxValue) << std::endl;
std::cout << "the_min is " << std::min( DBL_MAX, std::numeric_limits<double>::quiet_NaN()) << std::endl;
}
int main( int argc, char* argv[] )
{
testFunc();
return 0;
}
在调试中,我得到:
slope is nan
maxThreshold is 1.79769e+308
the_min is nan
the_min is 1.79769e+308
在发布时,我得到:
slope is nan
maxThreshold is 1.79769e+308
the_min is 1.79769e+308
the_min is nan
为什么我会在 Release 中得到与 Debug 不同的结果?
我已经检查过 Stack Overflow 帖子 Use of min and max functions in C++ ,它没有提到任何发布/调试差异。
我正在使用 Visual Studio 2015。
最佳答案
在 IEEE 754将 NAN 与任何东西进行比较总是会产生 false
,不管它是什么。
slope > 0; // false
slope < 0; // false
slope == 0; // false
而且,对你来说更重要的是
slope < DBL_MAX; // false
DBL_MAX < slope; // false
所以编译器似乎重新排序参数/使用 >
或 <=
而不是 <
,这就是为什么你会得到不同的结果。
例如,这些功能可以这样描述
发布:
double const& min(double const& l, double const r) {
return l <= r ? l : r;
}
调试:
double const& min(double const& l, double const& r) {
return r < l ? r : l;
}
std::min
上的要求 (LessThanComparable)除此之外,它们在算术上具有相同的含义。但是当您将它们与 NaN 一起使用时,它们会产生不同的结果。
关于c++ - 为什么发布/调试对 std::min 有不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39919069/