总下载代码的错误结果 [英] Incorrect Result of Total Download's Code

查看:75
本文介绍了总下载代码的错误结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码显示下载和上传的总数。当累积下载量超过2 GB时,就会出现问题,其结果是位数:

I use the following code to display the total download and upload. The problem arises when the cumulative download exceeds 2 GB, the result being the number of bits:

var
  Form1: TForm1;
  Downloaded, Uploaded:integer;

implementation

{$R *.dfm}

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  if Downloaded < 1024 then
  Recv.Caption           := FormatFloat(' + Recv: #,0 Bit',Downloaded)
  else if (Downloaded > 1024) and (Downloaded < 1048576) then
  Recv.Caption           := FormatFloat(' + Recv: #,##0.00 Kb',Downloaded/1024)
  else if (Downloaded > 1048576) and (Downloaded < 1073741824) then
  Recv.Caption           := FormatFloat(' + Recv: #,##0.00 Mb',Downloaded/1048576)
  else if (Downloaded > 1073741824) then
  Recv.Caption           := FormatFloat(' + Recv: #,##0.00 Gb', Downloaded/1073741824);

  if Uploaded < 1024 then
  Sent.Caption               := FormatFloat(' + Sent: #,0 Bit',Uploaded)
  else if (Uploaded > 1024) and (Uploaded < 1048576) then
  Sent.Caption               := FormatFloat(' + Sent: #,##0.00 Kb',Uploaded/1024)
  else if (Uploaded > 1048576) and (Uploaded < 1073741824) then
  Sent.Caption               := FormatFloat(' + Sent: #,##0.00 Mb',Uploaded/1048576)
  else if (Uploaded > 1073741824) then
  Sent.Caption               := FormatFloat(' + Sent: #,##0.00 Gb', Uploaded/1073741824);
end;

谁能解释为什么返回的结果不正确,更重要的是如何解决它,以便返回结果正确的结果?非常感谢...

Can anyone explain why it is returning the incorrect result and more importantly, how to fix it so it returns the correct result ? Thank you so much...

推荐答案

整数不能容纳大于2GB的值( MaxInt 为2147483647,约为1.99 GB)。如果尝试超过该值,它将溢出并变为负数。您需要改用 Int64

An Integer cannot hold a value greater than 2GB (MaxInt is 2147483647, which is ~1.99 GB). If you try to exceed that, it overflows and becomes negative. You need to use Int64 instead.

此外,您应该使用 B Bytes ,而不是 Bit 。您不是在下载位,而是在下载字节。

Also, you should be using B or Bytes instead of Bit. You are not downloading bits, you are downloading bytes.

尝试一下:

var
  Form1: TForm1;
  Downloaded, Uploaded: Int64;

implementation

{$R *.dfm}

function FormatBytes(ABytes: Int64): string;
begin
  if ABytes < 1024 then
    Result := FormatFloat('#,0 B', ABytes)
  else if ABytes < 1048576 then
    Result := FormatFloat('#,##0.00 Kb', ABytes / 1024)
  else if ABytes < 1073741824 then
    Result := FormatFloat('#,##0.00 Mb', ABytes / 1048576)
  else if ABytes < 1099511627776 then
    Result := FormatFloat('#,##0.00 Gb', ABytes / 1073741824)
  else
    Result := FormatFloat('#,##0.00 Tb', ABytes / 1099511627776);
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  Recv.Caption := ' + Recv: ' + FormatBytes(Downloaded);
  Send.Caption := ' + Sent: ' + FormatBytes(Uploaded);
end;

这篇关于总下载代码的错误结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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