减零(-0)等于C#中的零(0) [英] Is minus zero (-0) equivalent to zero (0) in C#

查看:49
本文介绍了减零(-0)等于C#中的零(0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,负零(-0)是否等于零(0)?

Is minus zero (-0) equivalent to zero (0) in C#?

推荐答案

对于整数,没有二进制表示形式会在0和-0之间产生差,因此按定义它们是相等的.

For integers, there is no binary representation that makes a difference between 0 and -0, so they are by definition equal.

对于IEEE浮点数,有负零和正零的区别.我进行了一些测试(.NET Framework 2.0的CLR,C#3),看来它们被认为是相等的,实际上这是根据IEEE 754标准所期望的行为.

For IEEE floating-point numbers, there is a distinction of negative and positive zero. I made some tests (CLR of .NET Framework 2.0, C# 3) and it seems that they are considered equal, which is actually the behavior expected according to the IEEE 754 standard.

这是我的测试代码,用于显示以下内容:

Here's my test code to show that:

    double minusOne = -1.0;
    double positiveZero = 0.0;
    double negativeZero = minusOne*positiveZero;
    Console.WriteLine("{0} == {1} -> {2}", positiveZero, negativeZero, positiveZero == negativeZero);
    Console.WriteLine("Binary representation is equal: {0}", BitConverter.DoubleToInt64Bits(positiveZero) == BitConverter.DoubleToInt64Bits(negativeZero));

返回:

0 == 0 -> True
Binary representation is equal: False

这篇关于减零(-0)等于C#中的零(0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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