大家好。
int[] ai1=new int[2] { 3514,3515 };
void average1()
{
List<int> aveList = new List<int> { ai1[0],ai1[1]};
double AveragLI = aveList.Average();
int AverLI = (int)Math.Round((double)AveragLI);
label1.Text = AverLI.ToString();
}返回3514;不应该是3515?
发布于 2013-05-04 09:22:54
Math.Round是罪魁祸首
int AverLI = (int)Math.Round((double)AveragLI);这就是我们所说的银行家的舍入,甚至是舍入。
关于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。
阅读this
为了避免这样做
int AverLI = (int)Math.Ceiling((double)AveragLI);发布于 2013-05-04 09:43:01
Math.Round的默认rounding scheme是所谓的银行家舍入(这是金融和统计领域的标准),其中中点值被舍入到最接近的偶数。看起来您希望中点值从零开始四舍五入(这可能是您在小学时学到的:如果它以5结束,则向上舍入)。
如果你只是担心它不能以一种可接受的方式工作,不用担心。如果你想从零开始四舍五入,你可以这样做:
int AverLI = (int)Math.Round((double)AveragLI, MidpointRounding.AwayFromZero);https://stackoverflow.com/questions/16369664
复制相似问题