我需要使用與默認“舍入到偶數”不同的中點舍入規則Mathf.Round()。Mathf.Round()沒有中點舍入的引數,所以我使用System.Math.Round().
C# 有不同的中點舍入策略,在此處指定:https ://docs.microsoft.com/en-us/dotnet/api/system.midpointrounding?view=net-6.0 。MidpointRounding.AwayFromZero并且(顯然)MidpointRounding.ToEven在 Unity 中作業,但其他人,即MidpointRounding.ToZero由于某種原因不作業(“CS0117:'MidpointRounding' 不包含'ToZero'的定義”)。
float firstN = ...
float lastN = ...
int begin = (int)Math.Round(firstN, MidpointRounding.AwayFromZero); //works
int end = (int)Math.Round(lastN, MidpointRounding.ToZero); //doesn't work
我絕對需要使用MidpointRounding.ToZero,真的沒有任何替代品。我將不得不再次重寫大部分代碼。撰寫我自己的舍入函式來解決這個問題聽起來也不好玩。
uj5u.com熱心網友回復:
MidpointRounding.ToZero,盡管被添加到MidpointRounding列舉中,但它也不會做你想讓它做的事情。它只是截斷數字的小數部分,為您提供離零不遠的最接近的整數:
2.4 ==> 2
2.5 ==> 2
2.6 ==> 2
-2.4 ==> -2
-2.5 ==> -2
-2.6 ==> -2
所以不幸的是,看起來你需要一個自定義的舍入方法,但這并不難:
int i = (d < 0) ? (int)Math.Floor(d 0.5) : (int)Math.Ceiling(d-0.5);
結果:
2.4 ==> 2
2.5 ==> 2
2.6 ==> 3
-2.4 ==> -2
-2.5 ==> -2
-2.6 ==> -3
uj5u.com熱心網友回復:
從記憶中,我相信定向舍入對于框架來說是相當新的。我不熟悉 Unity,但如果可能,您可能想嘗試更改目標框架。
或者,Math.Truncate應該提供相同的行為,我會爭辯更清晰的意圖。
int end = (int)Math.Truncate(lastN);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/424496.html
