Convert.ToInt32()  是我们经常使用的方法,但如果我们写如下的代码,能确定它的输出值么?

  var x = 7.5;
Console.WriteLine(7.5 + ": " + Convert.ToInt32(x));
x = 6.5;
Console.WriteLine(6.5 + ": " + Convert.ToInt32(x));

让我意外的是,它的输出为:

7.5: 8
6.5: 6

有点疑惑,所以用Reflector看下了代码:

 [__DynamicallyInvokable]
public static int ToInt32(double value)
{
if (value >= 0.0)
{
if (value < 2147483647.5)
{
int num = (int) value;
double num2 = value - num;
if ((num2 > 0.5) || ((num2 == 0.5) && ((num & ) != )))
{
num++;
}
return num;
}
}
else if (value >= -2147483648.5)
{
int num3 = (int) value;
double num4 = value - num3;
if ((num4 < -0.5) || ((num4 == -0.5) && ((num3 & ) != )))
{
num3--;
}
return num3;
}
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
} 0x1[__DynamicallyInvokable]
public static int ToInt32(double value)
{
if (value >= 0.0)
{
if (value < 2147483647.5)
{
int num = (int) value;
double num2 = value - num;
if ((num2 > 0.5) || ((num2 == 0.5) && ((num & ) != )))
{
num++;
}
return num;
}
}
else if (value >= -2147483648.5)
{
int num3 = (int) value;
double num4 = value - num3;
if ((num4 < -0.5) || ((num4 == -0.5) && ((num3 & ) != )))
{
num3--;
}
return num3;
}
throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}

6-15行的处理说明了问题,((num2 == 0.5) && ((num & 1) != 0) 判断如果是奇数,那么结果自增,否则不处理。Why? 为什么要这么处理? google了一下,发现.net的四舍五入都会使用“银行家四舍五入算法”:

The History section of the Wikipedia entry for Rounding has some statements about the role of "round to even" in computing. Interestingly, it appears "Bankers Rounding" has little evidence to state it was official in any sense of the word, so can only be chalked up as slang terminology.

It is only "more logical" if you subscribe to that rounding mechanism. Bankers rounding (which is the default in this case) is also perfectly logical.

Imagine if banks rounded up to the nearest penny for every fractional amount, they would make a lot less (lose a lot of, for the cynical) money with the millions upon millions of transactions that are processed daily. OK, so this example is cynical.

Going towards the nearest even number (or odd, but history chose otherwise) means that not every rounding resolution goes upsome can now go down. When you put this to the law of averages, it becomes a fair solution to use when considering who is responsible for paying for the extra half penny.

As for why this was chosen for the framework, this question attempts to address it:

Why does .NET use banker's rounding as default?

Of course, this all harks back to financial days and its applicability to integral numbers could be questioned, but why bother? Accept it, override it if you want to, just understand how it works.

请参阅:

http://stackoverflow.com/questions/11431793/convert-toint32-rounds-to-the-nearest-even-number

http://stackoverflow.com/questions/311696/why-does-net-use-bankers-rounding-as-default

Converter -> public static int ToInt32(double value) 你用对了么?的更多相关文章

  1. 【java】java.lang.Math:public static long round(double a)和public static int round(float a)

    package math; public class TestMath_round { public static void main(String[] args) { System.out.prin ...

  2. Java——int、double型数组常用操作工具类

    学了数组之后,感觉有好多操作需要经常去写,很不方便,因此自己做了一个工具类,方便调用,方法可能不全,希望大家可以添加,让我使用也方便一点儿. public class ArrayUtils { //求 ...

  3. 调用类java.lang.Math的成员方法"public static double random"运算下面表达式10000次,统计其中生成的整数0,1,2,.....20的个数分别是多少,并输出统计结果.(int)(Math.random()*20+0.5)

    public class Test2 { public static void main(String args[]){ int num; int count[]=new int[21]; for(i ...

  4. c#的中英文混合字符串截取 public static string SubString(string inputString, int byteLength)

    /// <summary>        /// c#的中英文混合字符串截取(区分中英文)        /// </summary>        /// <param ...

  5. 大话java基础知识一之为什么java的主函数入口必须是public static void

    为什么java的主函数入口必须是public static void main (String[] args); 很多写javaEE好几年的程序员经常会记得java的主函数就是这么写的,但实际上为什么 ...

  6. public static void main(String[] args){}函数诠释

    public static void main(String[] args){}函数诠释 主函数的一般写法如下: public static void main(String[] args){-} 下 ...

  7. 《Java程序员面试笔试宝典》之为什么需要public static void main(String[] args)这个方法

    public staticvoid main(String[] args)为Java程序的入口方法,JVM在运行程序的时候,会首先查找main方法.其中,public是权限修饰符,表明任何类或对象都可 ...

  8. 【java】计算一段代码执行时长java.lang.System类里的public static long currentTimeMillis()方法

    public class Test_currentTimeMillis { public static void main(String[] args) { long start=System.cur ...

  9. 主函数特别之处:public static void main(String[] args)

    public static void main(String[] args) public class Test_java {//主函数特殊之处 public static void main(Str ...

随机推荐

  1. SGU 261. Discrete Roots

    给定\(p, k, A\),满足\(k, p\)是质数,求 \[x^k \equiv A \mod p\] 不会... upd:3:29 两边取指标,是求 \[k\text{ind}_x\equiv ...

  2. MediaPlayer滑动不准的问题

    因为MediaPlayer在seekto是异步进行的,如果在滑动过程中暂停,会导致滑动不准确的情况,这时候就需要添加滑动完成的监听即setOnSeekCompleteListener

  3. 字符串匹配&Rabin-Karp算法讲解

    问题描述: Rabin-Karp的预处理时间是O(m),匹配时间O( ( n - m + 1 ) m )既然与朴素算法的匹配时间一样,而且还多了一些预处理时间,那为什么我们还要学习这个算法呢?虽然Ra ...

  4. 洛谷——P2035 iCow

    P2035 iCow 题目描述 被无止境的农活压榨得筋疲力尽后,Farmer John打算用他在MP3播放器市场新买的iCow来听些音乐,放松一下.FJ的iCow里存了N(1 <= N < ...

  5. 「2018山东一轮集训」 Tree

    为什么出题人这么毒瘤啊??!!一个分块还要带log的题非要出成n<=2*1e5....... 为了卡过最后两个点我做了无数常数优化,包括但不限于:把所有线段树改成 存差分的树状数组:把树剖求LC ...

  6. UVA 12338:Anti-Rhyme Pairs(后缀数组+ST表)

    [题目链接] click [题目大意] 给出一些字符串,询问查询任意两个字符串的最长公共前缀 [题解] 将字符串拼接,对拼接的字符串做后缀数组,对于查询的两个字符串, 只要在height数组上查询区间 ...

  7. 【构造】Codeforces Round #423 (Div. 1, rated, based on VK Cup Finals) B. High Load

    让你构造一棵树(给定了总结点数和总的叶子数),使得直径最小. 就先弄个菊花图(周围一圈叶子,中间一个点),然后平均地往那一圈放其他的点即可. #include<cstdio> using ...

  8. java乱码问题总结

    在基于Java的编程中,经常会碰到汉字的处里及显示的问题,比如一大堆乱码或问号. 这是因为JAVA中默认的编码方式是UNICODE,而中国人通常使用的文件和DB都是基于GB2312或者BIG5等编码, ...

  9. [BZOJ1002](FJOI 2007) 轮状病毒

    [题目描述] 给定n(N<=100),编程计算有多少个不同的n轮状病毒. [输入格式] 第一行有1个正整数n. [输出格式] 将编程计算出的不同的n轮状病毒数输出 [样例输入] 3 [样例输出] ...

  10. [转] Mybatis 示例之 SelectKey

    SelectKey在Mybatis中是为了解决Insert数据时不支持主键自动生成的问题,他可以很随意的设置生成主键的方式. 不管SelectKey有多好,尽量不要遇到这种情况吧,毕竟很麻烦. sel ...