Delphi下的四舍五入和取整,除了截取整數(shù)Trunc()之外,都是四舍六入五留雙,即銀行家算法。但是好像又不全是這么回事兒。要以實測為準(zhǔn)。 例如3.15和3.25,修約時應(yīng)分別得到3.2和3.2,而不是3.2和3.3。這個算法在大學(xué)物理實驗里也是這樣。但是也偶有爭議,說是不同的Delphi版本編譯器怎樣怎樣。我比較了Delphi7和Delphi XE11.1,結(jié)果是一樣的。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取整數(shù)部分' + inttostr(a)); a := round(2.5); showmessage('Round(2.5)四舍六入五留雙,得到2而不是3:' + inttostr(a)); b := simpleroundto(2.5, 0); showmessage('2.5取整,SimpleRounTo又開始傳統(tǒng)四舍五入3:' + floattostr(b)); b := simpleroundto(2.55, -1); showmessage('2.55留1位小數(shù),SimpleRounTo又開始傳統(tǒng)四舍五入2.6:' + floattostr(b)); b := simpleroundto(2.45, -1); showmessage('2.45留1位小數(shù),SimpleRounTo又開始傳統(tǒng)四舍五入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經(jīng)典四舍五入:' + inttostr(a)); a := RoundThief(124.5); showmessage('124.5取巧四舍五入:' + inttostr(a)); //showmessage('33.025四舍五入:' + floattostr(RoundTo(33.025,-2))); end;
end.

|