首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# - (int)Math.Round((double)(3514 + 3515)/2) =3514?

C# - (int)Math.Round((double)(3514 + 3515)/2) =3514?
EN

Stack Overflow用户
提问于 2013-05-04 09:21:07
回答 2查看 670关注 0票数 1

大家好。

代码语言:javascript
复制
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?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-05-04 09:22:54

Math.Round是罪魁祸首

代码语言:javascript
复制
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

为了避免这样做

代码语言:javascript
复制
int AverLI = (int)Math.Ceiling((double)AveragLI);
票数 3
EN

Stack Overflow用户

发布于 2013-05-04 09:43:01

Math.Round的默认rounding scheme是所谓的银行家舍入(这是金融和统计领域的标准),其中中点值被舍入到最接近的偶数。看起来您希望中点值从零开始四舍五入(这可能是您在小学时学到的:如果它以5结束,则向上舍入)。

如果你只是担心它不能以一种可接受的方式工作,不用担心。如果你想从零开始四舍五入,你可以这样做:

代码语言:javascript
复制
int AverLI = (int)Math.Round((double)AveragLI, MidpointRounding.AwayFromZero);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16369664

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档