Why do TTime comparisons give unexpected results?

我的未来我决定 提交于 2019-12-10 14:43:37

问题


I have observed some kind of weird behaviour regarding the EncodeDateTime and EncodeTime methods and I am seeking some explanation.

procedure SomeTestCase;
var
    time: TTime;
    dateTime: TDateTime;
begin
    time := EncodeTime(8, 0, 0, 0);
    date := EncodeDateTime(2012, 11, 2, 8, 0, 0, 0);

    Assert(time = TimeOf(date)); //Fails
end;

What I've found is that date's hour portion evaluates to 7:59:59 instead of 8:00:00. But if I set the hour portion of time and date to 9, the assert passes and date evaluates to the expected value. Some hours work while some others don't. Can somebody explain me what is going on?


回答1:


A time value (TTime, TDate, TDateTime) is actually a double (that is, a floating-point value), with the date encoded in the integer part, and the time encoded in by fractional part. And it is always risky to test equality of floating-point values.

You can use SameTime(time, date) instead. This compensates correctly for 'numerical fuss': Result := Abs(Frac(A) - Frac(B)) < OneMillisecond;



来源:https://stackoverflow.com/questions/13201535/why-do-ttime-comparisons-give-unexpected-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!