2017-03-02 59 views
0

我超载运营商><==在一个简单的时间等级。运营商==超载功能失败

double exchange_time::seconds_from_midnight() const { 
    return seconds + minutes * 60.0 + hours * 3600.0 + milliseconds/1000.0; 
} 

bool exchange_time::operator<(const exchange_time& other) const 
{ 
    return seconds_from_midnight() < other.seconds_from_midnight(); 
} 

bool exchange_time::operator>(const exchange_time& other) const 
{ 
    return seconds_from_midnight() > other.seconds_from_midnight(); 
} 

bool exchange_time::operator==(const exchange_time& other) const 
{ 
    return seconds_from_midnight() == other.seconds_from_midnight(); 
} 

><工作完美。然而==产生错误,我的测试失败:

TEST_F(exchange_time_test, comparison) { 
    exchange_time et1, et2; 
    et1.set("93500001"); 
    et2.set("93500123"); 
    EXPECT_TRUE(et2 > et1); 
    EXPECT_TRUE(et1 < et2); 
    EXPECT_TRUE(et2 == et2); 
} 

有什么我失踪了吗?

这里是我的声明:

class exchange_time { 
    public: 
     void set(string timestamp); 
     unsigned short int get_milliseconds() { return milliseconds; } 
     unsigned short int get_seconds() { return seconds; } 
     unsigned short int get_minutes() { return minutes; } 
     unsigned short int get_hours() { return hours; } 
     double seconds_from_midnight() const; 
     bool operator<(const exchange_time& other) const; 
     bool operator>(const exchange_time& other) const; 
     bool operator==(const exchange_time& other) const; 
    private: 
     unsigned short int milliseconds; 
     unsigned short int seconds; 
     unsigned short int minutes; 
     unsigned short int hours; 
}; 
+5

'double seconds_from_midnight();''double's是不精确的。一个可以是1.000000000001,另一个可以是0.9999999999999。更多这里:[浮点数学是否被破坏?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – user4581301

+1

[浮点数学是否被破坏?](http:/ /stackoverflow.com/questions/588004/is-floating-point-math-broken) –

+1

但在这种情况下字面意思是相同的数字 – user2717954

回答

4

决不比较为双号的平等。检查它们是否几乎相等。最常见的方法是使用epsilon来比较值。

bool exchange_time::operator==(exchange_time other) 
{ 
    return abs(seconds_from_midnight() - other.seconds_from_midnight()) < EPS; 
} 

EPS是一个很小的值。如果你需要准确的比较,你需要定义你自己的分数类。

EDIT
EPS代表ε,其被定义为通过的Dictionary.com东西一个非常小的,不显着,或可忽略的量。

+1

建议将“eps”扩展为完整的单词:“epsilon”。这将使读者通过网络搜索更容易获得更多信息。 – user4581301

+0

@ user4581301好的。我最初添加了EPS,因为它在竞争性的编程文化中非常流行,几乎每个人几乎每天都在使用它。我不知道有人可能会抱怨:D – silentboy