Math.Round返回四舍五入为奇数值,但几轮下来,即使 [英] Math.Round returning a rounded up for odd values but rounds down for even

查看:193
本文介绍了Math.Round返回四舍五入为奇数值,但几轮下来,即使的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到使用数学轮
浮点我发现下面的

  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 takes MidpointRounding 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆