Why does 0.5 rounded with MidpointRounding.AwayFromZero result in 0?

一曲冷凌霜 提交于 2020-01-13 10:16:09

问题


Why does this result in 0 and not 1?

Math.Round(0.5, 0, MidpointRounding.AwayFromZero)

Here's an example: http://ideone.com/ayMVO


回答1:


Normally, with issues like that, it's because the number cannot be represented exactly in IEEE754 - it's most likely it's being converted to 0.4999999999... or something like that which would round to zero.

However, 0.5 (1/2) is exactly representable in IEEE754 so that's not the case here.

It's possible that the compiler made a mistake in converting the text to a number but I would think that unlikely. In fact, when I compile and run the following in VC#2010:

using System;
namespace ConsoleApplication1 {
    class Program {
        static void Main (string[] args) {
            Console.WriteLine (Math.Round (0.5, 0, MidpointRounding.AwayFromZero));
        }
    }
}

I get the output of 1 as expected.

So I don't think your question is quite complete. Now it may be that your actual situation doesn't use a hard-coded value of 0.5 but instead uses a variable which you believe to be 0.5.

My answer to that would be that, while it may be close to 0.5 (certainly close enough that a simple WriteLine of it might output 0.5), it's probably a touch below 0.5, which would cause my comments in the first paragraph above to once again kick in.


Based on your link, it appears that Mono 2.8 may have a bug. I'd suggesting seeking support from the developers (or just raising a bug report) here.

Actually, having tried it locally with gmcs 2.6.7, it's definitely a bug. That exact code compiled okay but generates 0 rather than 1. A bug report has been raised, and I've added my own information to it.




回答2:


This also returns 1.0 for me when I debugged it.

Math.Round(0.5, 0, MidpointRounding.AwayFromZero)



回答3:


0.5 is a double.

If you do

Math.Round(0.5M, 0, MidpointRounding.AwayFromZero)

It will work as expected



来源:https://stackoverflow.com/questions/9475448/why-does-0-5-rounded-with-midpointrounding-awayfromzero-result-in-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!