如何在delphi中比较double? [英] How to compare double in delphi?

查看:345
本文介绍了如何在delphi中比较double?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正面临数据类型双重比较的问题:

We are facing issue with data type double comparison:

if(p > pmax) then
begin
  Showmessage('');
end

如果两个值都为100(p = 100和pmax = 100)

If both values are 100 (p=100 and pmax = 100), then also it is going inside if clause.

推荐答案

有几个比较双打的问题。一个问题是,你所看到的并不完全是由于四舍五入而得到的。您可以拥有99.999999996423和100.00000000001632,它们都被舍入到100,但是它们不相等。

There are several probles with comparing doubles. One problem is that what you see is not exactly what you get due to rounding. You can have 99.999999996423 and 100.00000000001632 which are both rounded to 100 but they are not equal.

解决方案是使用边距。因此,如果两个双打的差异在边距范围内,您可以接受它们相等。

The solution is to use a margin. So that if the difference of the two doubles lies within the margin, you accept them as equal.

您可以使用margin作为可选参数创建IsEqual函数: / p>

You can create an IsEqual function using the margin as an optional parameter:

function IsEqual(const ANumber1, ANumber2: Double; const AMargin: Double = cMargin): Boolean;
begin
  Result := Abs(ANumber1-ANumber2) <= AMargin;
end;

这篇关于如何在delphi中比较double?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆