2017-08-28 40 views
-3

如何在C#中將此循環表達爲數學表達式?如何以數學方式表示此功能

private string FormatBytes(long bytes) 
{ 
    string[] Suffix = { "B", "KB", "MB", "GB", "TB" }; 
    int i; 
    double dblSByte = bytes; 
    for (i = 0; i < Suffix.Length && bytes >= 1024; i++, bytes /= 1024) 
    { 
     dblSByte = bytes/1024.0; 
    } 

    return String.Format("{0:0.##} {1}", dblSByte, Suffix[i]); 
} 
+8

定義「數學」。 – CodeCaster

+0

使用數學表達函數的結果 –

+0

像這樣:https://puu.sh/xl6VX/155c777cdf.png –

回答

1

你可以先制定出最接近較小功率的1024至數數學計算這個

int power = (int) Math.Log(bytes, 1024) 

然後你就可以限制號碼後綴的數量,所以你不要去過去的數組的末尾:

int power = Math.Min(Suffix.Length-1, (int) Math.Log(bytes, 1024)); 

然後你的工作,你應該基於權力劃分一下原來的號碼:

return string.Format("{0:f1}{1}", bytes/div, Suffix[power]); 

把所有這一切在一起(和扔在 「PB」 爲PB級):

double div = Math.Pow(1024, power); 

然後你可以使用後綴爲1024所指定的電力格式化字符串

private string FormatBytes(long bytes) 
{ 
    string[] Suffix = { "B", "KB", "MB", "GB", "TB", "PB" }; 
    int power = Math.Min(Suffix.Length-1, (int) Math.Log(bytes, 1024)); 
    double div = Math.Pow(1024, power); 

    return string.Format("{0:f1}{1}", bytes/div, Suffix[power]); 
} 

Et瞧!無需使用循環就可以數學計算。

(我敢打賭,這不是可測量比循環更快,雖然...)

如果你想你可以擴展後綴列包括「exobyte」,然後它會很好地工作一路int.MaxValue,這是8.0EB。