加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#错误从double转换为int32

发布时间:2020-12-15 23:55:23 所属栏目:百科 来源:网络整理
导读:using NUF = NUnit.Framework;[NUF.Test]public void DifferentCastingTest() { NUF.Assert.That((int)0.499999D,NUF.Is.EqualTo(0)); NUF.Assert.That((int)0.500000D,NUF.Is.EqualTo(0)); // !!! row 1 NUF.Assert.That((int)1.499999D,NUF.Is.EqualTo(1))
using NUF = NUnit.Framework;
[NUF.Test]public void DifferentCastingTest() {
     NUF.Assert.That((int)0.499999D,NUF.Is.EqualTo(0)); 
     NUF.Assert.That((int)0.500000D,NUF.Is.EqualTo(0)); // !!! row 1
     NUF.Assert.That((int)1.499999D,NUF.Is.EqualTo(1)); 
     NUF.Assert.That((int)1.500000D,NUF.Is.EqualTo(1)); // !!! row 2

     NUF.Assert.That(System.Convert.ToInt32(0.499999D),NUF.Is.EqualTo(0)); 
     NUF.Assert.That(System.Convert.ToInt32(0.500000D),NUF.Is.EqualTo(0)); // !!! 
     NUF.Assert.That(System.Convert.ToInt32(1.499999D),NUF.Is.EqualTo(1)); 
     NUF.Assert.That(System.Convert.ToInt32(1.500000D),NUF.Is.EqualTo(2)); //!!! row 3
  }

通过转换和Convert.ToInt32(参见第2行和第3行)以不同方式转换相同的double值(1.5D),并且在不同模式下舍入两个具有相同尾数(0.5和1.5)的double(参见第1行和第2行) .
这是一个错误吗?

解决方法

不,这是记录在案的行为. Convert.ToInt32(double)向上或向下舍入一个数字,中间点向四舍五入到均匀:

Return Value

value,rounded to the nearest 32-bit signed integer. If value is halfway between two
whole numbers,the even number is returned; that is,4.5 is converted to 4,and 5.5 is
converted to 6.

从C#3规范的第6.2.1节开始,铸造总是向零舍入(例如,1.8轮到1)

Otherwise,the source operand is
rounded towards zero to the nearest
integral value. If this integral value
is within the range of the destination
type then this value is the result of
the conversion.

请注意,这不仅仅是关于银行家的四舍五入:它是关于一般的舍入:(int)0.9和Convert.ToInt32(0.9)之间存在差异.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读