为什么用MidpointRounding.AwayFromZero将0.5舍入为0? [英] Why does 0.5 rounded with MidpointRounding.AwayFromZero result in 0?

查看:702
本文介绍了为什么用MidpointRounding.AwayFromZero将0.5舍入为0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这会导致0而不是1?

Why does this result in 0 and not 1?

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

这里是一个示例: http://ideone.com/ayMVO

推荐答案

通常,由于类似问题,这是因为该数字无法在IEEE754中准确表示-最有可能是将其转换为0.4999999999 ...之类的东西会舍入为零.

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.

但是,在IEEE754中可以精确地表示0.5(1/2) ,所以这里不是这种情况.

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

编译器在将文本转换为数字时可能犯了一个错误,但我认为这不太可能.实际上,当我在VC#2010中编译并运行以下代码时:

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));
        }
    }
}

我得到了预期的1输出.

因此,我认为您的问题并不完整.现在,可能是您的 actual 情况没有使用0.5的硬编码值,而是使用了一个您相信 为0.5的变量.

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.

我的回答是,虽然它可能 close 到0.5(肯定足够接近以至于它的简单WriteLine可能输出0.5),但它可能是下面的 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.

根据您的链接,看来Mono 2.8可能有一个错误.我建议在此处.

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.

实际上,在gmcs 2.6.7本地进行了尝试,这绝对是一个错误.该确切的代码可以编译,但是会生成0而不是1.一个错误报告已经提出,我已经添加了我自己的信息.

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.

这篇关于为什么用MidpointRounding.AwayFromZero将0.5舍入为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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