ABS函数在Delphi中失败

ABS函数在Delphi中失败

本文介绍了ABS函数在Delphi中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Delphi6或Delphi 2010中,声明货币类型(vtemp1,vtemp2)的两个变量,并给它们输入0.09的值。
使用ABS函数嵌入一个变量并将其与另一个进行比较。
编译器
手表显示与abs(vtemp1)和vtemp2相同的值时,您期待进行比较以产生积极的结果。
奇怪的是if语句失败!!!

In Delphi6 or in Delphi 2010, declare two variables of type Currency (vtemp1,vtemp2) and feed them a value of 0.09.Embed one of the variables with the ABS function and compare it to the other.You would expect for the comparison to yield a positive result as the compilerwatch reveals the same value for abs(vtemp1) and vtemp2.Oddly the if statement fails!!!

注意:
- 这个问题只有在处理
号0.09(尝试几个其他近值显示正常结果)
- 将变量声明为Double而不是货币,问题停止存在。

Notes:-This problem is experienced only when dealing with thenumber 0.09 (trying several other near values revealed normal results)-Declaring the variable as Double instead of currency, the problem ceases to exist.

推荐答案

我认为原因是类型转换。 abs()函数返回实际结果,所以 currency 投射到真实。看看文档:

I think that the reason is type conversions. Abs() function returns real results, so currency variable casts to real. Take a look at documentation:

所以货币是固定的,实际是浮点。
您的问题的示例代码是:

so Currency is fixed and real is floating-point.Sample code for your question is :

program Project3;
{$APPTYPE CONSOLE}

const VALUE = 0.09;
var a,b  : currency;
begin
    a := VALUE;
    b := VALUE;

    if a = Abs(b) then writeln('equal')
    else writeln('not equal', a - Abs(b));

    readln;
end.

生成不等于结果,因为类型转换;

produces not equal result, because of type conversions;

尝试添加 x:real ,然后调用 x:= abs(b); ,将 x 添加到手表列表中,选择它,然后按编辑手表,然后选择浮点。 X 成为 0.899 ... 967

Try to add x : real, then call x := abs(b);, add x to watches list, select it and press Edit watch, then select Floating point. X becomes 0.899...967.

不只有 0.09 产生这样的结果。您可以尝试此代码检查:

not only 0.09 value produces such result. you can try this code to check:

    for i := 0 to 10000 do begin
        a := a + 0.001;
        b := a;
        if a <> abs(b) then writeln('not equal', a);
    end;

所以,如果你需要货币变量的绝对值 - 只要做。不要使用浮点数 abs()

so, if you need absolute value of Currency variable - just do it. don't use floating-point abs():

    function Abs(x : Currency):Currency; inline;
    begin
        if x > 0 then result := x
        else result := -x;
    end;

这篇关于ABS函数在Delphi中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 08:26