Math.Round返回四舍五入为奇数值,但几轮下来,即使 [英] Math.Round returning a rounded up for odd values but rounds down for even
问题描述
我试图找到使用数学轮
浮点我发现下面的
0.5 - > 0
1.5 - > 2
2.5 - > 2
3.5 - > 4
等。
我相信这是由于浮点错误,但不太清楚如何。
我怎样才能解决这个如此偶数轮是否正确?
从的文档;
最近的一个整数。 如果的小数部分是两个整数,其中之一是,即使和其他奇怪,那么
连,则返回数。请注意,此方法返回的中间
双
,而不是整型。
块引用>
Math.Round
方法有一些重载这需要的MidpointRounding
作为一个参数,你可以,如果它是中间两个数字之间指定舍入值。AwayFromZero
当一个号码是中途两个人之间,它朝向$ b $四舍五入b是远离零最接近的数字。
块引用>
ToEven
在一些介于两个人之间,它向最接近的偶数的
四舍五入。
块引用>I am trying to found a float using math round I found the following
0.5 --> 0 1.5 --> 2 2.5 --> 2 3.5 --> 4
and so on. I believe this is due to floating point error, but not quite sure how. How can I get around this so even numbers round properly?
解决方案From documentation;
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. Note that this method returns a Double instead of an integral type.
Math.Round
method has some overloads that takesMidpointRounding
as a parameter which you can specify the rounding value if it is midway between two numbers.AwayFromZero
When a number is halfway between two others, it is rounded toward the nearest number that is away from zero.
ToEven
When a number is halfway between two others, it is rounded toward the nearest even number.
这篇关于Math.Round返回四舍五入为奇数值,但几轮下来,即使的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!