EQ的double或float总计错误

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_NEAR DoubleEq 匹配器。浮点运算可能会导致rounding errors,这会使结果略有不同。

关于c++ - EXPECT_EQ的double或float总计错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15128510/

10-09 23:27