C# – (int)Math.Round((double)(3514 + 3515)/ 2)= 3514?
大家好。
int[] ai1=new int[2] { 3514,3515 }; void average1() { List aveList = new List { ai1[0],ai1[1]}; double AveragLI = aveList.Average(); int AverLI = (int)Math.Round((double)AveragLI); label1.Text = AverLI.ToString(); }
返回3514; 不应该是3515?
Math.Round是罪魁祸首
int AverLI = (int)Math.Round((double)AveragLI);
我们称之为Banker的Rounding甚至四舍五入。
关于Math.Round的信息说
The integer nearest a. If the fractional component of a is halfway between two integers, one of which is even and the other odd, then the even number is returned.
3514.5四舍五入为3514,3515.5也四舍五入为3514。
读这个
为了避免这样做
int AverLI = (int)Math.Ceiling((double)AveragLI);
Math.Round
的默认舍入方案是所谓的银行家舍入(这是财务和统计区域的标准),其中中点值四舍五入到最接近的偶数。 看起来你期望中点值从零开始(这可能是你在小学里教过的那种:如果它以5结尾,向上舍入)。
如果您只是担心它不能以可接受的方式工作,请不要担心。 如果你希望它从零开始,你可以这样做:
int AverLI = (int)Math.Round((double)AveragLI, MidpointRounding.AwayFromZero);