gpt4 book ai didi

从 double 到 int32 的 C# 错误转换

转载 作者:行者123 更新时间:2023-11-30 13:29:04 24 4
gpt4 key购买 nike

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
}

相同的 double 值 (1.5D) 通过转换和 Convert.ToInt32 以不同的方式转换(参见第 2 和 3 行),并且具有相同尾数的两个 double(0.5 和 1.5)以不同的方式舍入(参见第 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.

转换总是向零舍入(例如,1.8 舍入为 1)- 来自 C# 3 规范的第 6.2.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.9Convert.ToInt32(0.9) 之间是有区别的.

关于从 double 到 int32 的 C# 错误转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2950122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com