C#:四捨五入程式
阿新 • • 發佈:2018-12-15
問題
C#中的Math.Round()不是"四捨五入"法;
其實在VB、VBScript、C#、J#、T-SQL中Round函式採用的都是 Banker's rounding(銀行家演算法),即:四捨六入五取偶。
這是IEEE的規範;
.NET 2.0 開始,Math.Round 方法提供了一個列舉選項 MidpointRounding.AwayFromZero 可以用來實現傳統意義上的"四捨五入"。即: Math.Round(4.5, MidpointRounding.AwayFromZero) = 5。
上取整、下取整
程式
//五舍六入 //0.5 可以任意設定 0.2, 0.3... int RoundFun(double X) { double a; a = X - (Math.Floor(X)); if (a > 0.5) return ((int)Math.Ceiling(X));//不小於X的最小整數 1.4-- 2 else return ((int)Math.Floor(X));//不大於X的最大整數 1.4-- 1 }
參考文章
1. https://blog.csdn.net/a22698488/article/details/53585563
2. https://www.cnblogs.com/dianli_jingjing/p/7065122.html