2011-03-12 41 views
1

這段代碼有什麼問題?我可以得到正確的價值? DrvUsg總是變爲零。請幫我拿這個代碼工作。幫我得到這段代碼工作

Computer cmp = new Computer(); 
    string SysDrv = System.Environment.SystemDirectory.Substring(0, 2); 
    UInt64 TotalDrv = Convert.ToUInt64(cmp.FileSystem.GetDriveInfo(SysDrv).TotalSize/1024/1024); 
    UInt64 FreeDrv = Convert.ToUInt64(cmp.FileSystem.GetDriveInfo(SysDrv).AvailableFreeSpace/1024/1024); 
    UInt64 UsedDrv = (TotalDrv - FreeDrv); 
    UInt64 DrvUsg = Convert.ToUInt64((UsedDrv/TotalDrv) * 100); 
    TrkDrvUsg.Value = (int)DrvUsg; 
    LblDrvUsg.Text = (String.Format("System drive usage: {0}%", DrvUsg)); 
+1

這是一個非常惡臭的整數除法惡臭。 – BoltClock 2011-03-12 05:02:40

回答

5

這就是問題所在:

UInt64 DrvUsg = Convert.ToUInt64((UsedDrv/TotalDrv) * 100); 

這將工作:

UInt64 DrvUsg = Convert.ToUInt64(100 * UsedDrv/TotalDrv); 

你正在做一個整數除法,這將始終四捨五入,因爲TotalDrvUsedDrv結果大總是零。

+0

哇超級它的工作感謝BrokenGlass :) – Gayan 2011-03-12 05:06:55

+0

+1驚人的觀察! – 2011-03-12 07:40:57