2015-05-24 68 views
0

我使用以下代碼來顯示總下載和上載。當累計下載超過2 GB,其結果是比特數的問題出現了:總下載代碼不正確

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; 

任何人都可以解釋爲什麼它返回不正確的結果,更重要的是,如何解決它,所以它返回正確的結果?非常感謝...

回答

9

一個Integer不能保存大於2GB的值(MaxInt是2147483647,這是〜1.99 GB)。如果你試圖超過它,它會溢出並變成負面的。您需要改用Int64

此外,您應該使用BBytes而不是Bit。你不下載位,你正在下載字節。

試試這個:

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; 
+0

雷米先生,謝謝你這麼多。我已經成功編譯了它。現在,我試圖下載一些GB文件。順便說一句,你的代碼在'Result:= FormatFloat('#,## 0.00 Gb',ABytes/1073741824);'編譯我的應用時會導致錯誤。 – Johan

+0

我刪除了違規分號。 –

+0

雷米爵士,我很抱歉,但結果無法正常工作。當累計下載超過1 GB時,結果爲** 0.00 Tb **。你能解決它嗎?非常感謝! – Johan