如何获得-0结果浮点计算,并在C#中的+ 0区别呢? [英] How to get a -0 result in floating point calculations and distinguish it from +0 in C#?

查看:238
本文介绍了如何获得-0结果浮点计算,并在C#中的+ 0区别呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MSDN文档中提到,双击类型包括负零。然而,无论 -1.0 / double.PositiveInfinity -double.Epsilon / 2 显示返回正常0(和比较等于它)。我怎样才能得到-0?

The MSDN documentation mentions that double type includes negative zero. However, both -1.0 / double.PositiveInfinity and -double.Epsilon / 2 appear to return normal 0 (and compare equal to it). How can I get -0?

推荐答案

下面是两个之间的区别,而不检查该位的实际例子。 MSDN链接这里和的这里帮助我在构建这个例子

Here is a practical example of differentiating between the two without examining the bits. MSDN links here and here assisted me in constructing this example.

static void Main(string[] args)
{
    float a = 5 / float.NegativeInfinity;
    float b = 5 / float.PositiveInfinity;
    float c = 1 / a;
    float d = 1 / b;
    Console.WriteLine(a);
    Console.WriteLine(b);
    Console.WriteLine(c);
    Console.WriteLine(d);
}



输出:

Output:

0
0
-Infinity
Infinity

请留意-0和0这两个看起来一样的比较,输出等,但如果你被他们1分,你会得到一个-Infinity或无穷大,这取决于你零有。

Take note that -0 and 0 both look the same for comparisons, output, etc. But if you divide 1 by them, you get a -Infinity or Infinity, depending on which zero you have.

这篇关于如何获得-0结果浮点计算,并在C#中的+ 0区别呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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