Trunc() function

为君一笑 提交于 2020-01-13 02:10:28

问题


look the follow code, why the result of Trunc function is different?

procedure TForm1.Button1Click(Sender: TObject);
var
  D: Double;
  E: Extended;
  I: Int64;
begin
  D := Frac(101 / 100) * 100;
  E := Frac(101 / 100) * 100;
  I := Trunc(D);
  ShowMessage('Trunc(Double): ' + IntToStr(I));  // Trunc(Double): 1
  I := Trunc(E);
  ShowMessage('Trunc(Extended): ' + IntToStr(I)); // Trunc(Extended): 0
end;

回答1:


Formatting functions don't always display the actual numbers (data).
Real numbers and precision can be tricky.

Check out this code where I use more precision on what I want to see on the screen:

  D := Frac(101 / 100);
  E := Frac(101 / 100);
  ShowMessage(FloatToStrF(D, ffFixed, 15, 20));
  ShowMessage(FloatToStrF(E, ffFixed, 18, 20));

It appears that D is something like 0.010000000000 while E is like 0.00999999999.

Edit: Extended type has better precision than Double type. If we try to display the values of D and E with FloatToString() we'll probably get the same result, even though the actual values are not the same.




回答2:


Note Nick D’s answer. He is right when saying that

It appears that D is something like 0.010000000000 while E is like 0.00999999999.

The answer however, is not in formatting function. This is how the float calculations are done. Computers simply do not understand float numbers (since there is infinite amount of numbers between 0 and 1, while computers operate on finite number of bits and bytes), and every Double or Extended variable in Delphi (and most other languages) is just an approximation (with some really rare exceptions).

You can read more of it on Wikipedia: Floating point and Fixed-point



来源:https://stackoverflow.com/questions/1398295/trunc-function

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