c – EXPECT_EQ对于double或float的总和出错

前端之家收集整理的这篇文章主要介绍了c – EXPECT_EQ对于double或float的总和出错前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我无法理解为什么测试用例在双重数字或浮点数的情况下失败.它对于整数数据类型非常精细.

// simple_method.h中的方法

double sum ( double a,double b)
{
    double res = a+b;
    return res;
}

//这个方法的测试用例

TEST(simpleSum,sumOfFloat)
{
    EXPECT_EQ(4.56,sum(0.56,4.0));
}

//输出

Running main() from gtest_main.cc
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from simpleSum
[ RUN      ] simpleSum.sumOfFloat
/home/pcadmin/Desktop/so/so3/simple_method_test.cpp:7: Failure
Value of: sum(0.56,4.0)
  Actual: 4.56
Expected: 4.56
[  Failed  ] simpleSum.sumOfFloat (0 ms)
[----------] 1 test from simpleSum (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[  PASSED  ] 0 tests.
[  Failed  ] 1 test,listed below:
[  Failed  ] simpleSum.sumOfFloat

 1 Failed TEST

解决方法

改为使用 EXPECT_NEARDoubleEq匹配器.浮点操作可能导致 rounding errors,这使得结果有所不同.

猜你在找的C&C++相关文章