分享

DELPHI XE11.1的几个数学取整

 新用户5228KeDY 2022-05-04 发布于北京

Delphi下的四舍五入和取整,除了截取整数Trunc()之外,都是四舍六入五留双,即银行家算法。但是好像又不全是这么回事儿。要以实测为准。

例如3.15和3.25,修约时应分别得到3.2和3.2,而不是3.2和3.3。这个算法在大学物理实验里也是这样。但是也偶有争议,说是不同的Delphi版本编译器怎样怎样。我比较了Delphi7和Delphi XE11.1,结果是一样的。Round()在四舍六入,而SimpleRoundTo()仍然在四舍五入。

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;


implementation
uses math;
{$R *.dfm}

function RoundClassic(R: Real): Int64;
begin
  Result:= Trunc(R);
  if Frac(R) >= 0.5 then
    Result:= Result + 1;
end;

function RoundThief(R: Real): Int64;
begin
  R:=R+0.0000000000001;
  Result:= Trunc(R);
  if Frac(R) >= 0.5 then
    Result:= Result + 1;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  a: integer;
  b: real;
begin
  a := Trunc(0.35 * 10);
  showmessage('3.5取整数部分' + inttostr(a));
  a := round(2.5);
  showmessage('Round(2.5)四舍六入五留双,得到2而不是3:' + inttostr(a));
b := simpleroundto(2.5, 0);
  showmessage('2.5取整,SimpleRounTo又开始传统四舍五入3:' + floattostr(b));
  b := simpleroundto(2.55, -1);
  showmessage('2.55留1位小数,SimpleRounTo又开始传统四舍五入2.6:' + floattostr(b));
  b := simpleroundto(2.45, -1);
  showmessage('2.45留1位小数,SimpleRounTo又开始传统四舍五入2.5:' + floattostr(b));
  a := ceil(123.4);
  showmessage('123.4向上取整:' + inttostr(a));
  a := ceil(-123.4);
  showmessage('-123.4向上取整:' + inttostr(a));
  a := floor(123.4);
  showmessage('123.4向下取整:' + inttostr(a));
  a := floor(-123.4);
  showmessage('-123.4向下取整:' + inttostr(a));
    a := RoundClassic(124.5);
  showmessage('124.5经典四舍五入:' + inttostr(a));
    a := RoundThief(124.5);
  showmessage('124.5取巧四舍五入:' + inttostr(a));
  //showmessage('33.025四舍五入:' + floattostr(RoundTo(33.025,-2)));
end;

end.

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多