爲什麼: Console.WriteLine(Math.Floor(128.766*1000));
爲什麼我需要做的浮點運算與Math.floor
產生不同的結果:
Console.WriteLine(Math.Floor((decimal)128.766*1000));
當然,正確答案是128766是否有工作int或小數。 (我熟悉鑄造到除法例如小數。)
我使用.NET 4.5 C#
爲什麼: Console.WriteLine(Math.Floor(128.766*1000));
爲什麼我需要做的浮點運算與Math.floor
產生不同的結果:
Console.WriteLine(Math.Floor((decimal)128.766*1000));
當然,正確答案是128766是否有工作int或小數。 (我熟悉鑄造到除法例如小數。)
我使用.NET 4.5 C#
第一行使用浮點數學,這是不準確的。 128.766*1000
可能評估爲128765.99999999999
或類似的東西。
Math.Floor
將其下降爲128765
。
但是,在第二行中,首先將結果轉換爲decimal
,然後再將Math.Floor
轉換爲decimal
。由於decimal
是128位並且具有較小的範圍,所以轉換爲十進制可以消除這種不準確性。有關更多信息,請參見here。當您將128765.9999999999
轉換爲decimal
時,它變成了128766
。
http://csharpindepth.com/Articles/General/FloatingPoint.aspx。讀這個。一個Маth.Floor返回十進制其他的double,這就是爲什麼。 – mybirthname
運行以下提示:['Console.WriteLine((128.766 * 100).ToString(「e20」))'](https://ideone.com/s01m87) – dasblinkenlight