简体   繁体   English

C#打印浮点值-0.0错误

[英]C# is printing float value of -0.0 wrong

Console.WriteLine(" 0.0 float: 0x00000000, {0}", (float)0x00000000);
Console.WriteLine("-0.0 float: 0x80000000, {0}", (float)0x80000000);

C# prints 0.0 for the first one, and instead of -0.0 prints 2.147484E+09 which is not what I expected. C#为第一个打印0.0,而不是-0.0打印2.147484E + 09,这不是我期望的。 According to this online IEEE-754 floating-point format converter 0x80000000 should be a -0.0, since floating-point format uses sign-magnitude format, which supports -0.0. 根据此在线IEEE-754浮点格式转换器,0x80000000应该为-0.0,因为浮点格式使用支持-0.0的符号幅度格式。

https://www.h-schmidt.net/FloatConverter/IEEE754.html https://www.h-schmidt.net/FloatConverter/IEEE754.html

How do we get C# to print -0.0 for UInt32 bit pattern of 0x80000000? 如何使C#为0x80000000的UInt32位模式打印-0.0?

When you do (float)0x80000000 you are taking an integer value (0x80000000 = 2.147484E+09) and casting it to float (the value is the same, but now it's a float). 当您执行(float)0x80000000您正在获取一个整数值(0x80000000 = 2.147484E + 09)并将其强制转换为float(值相同,但现在是float)。 What you want is take the byte array and interpret it as float: 您想要的是获取字节数组并将其解释为float:

uint l = (uint)0x80000000;
float f = BitConverter.ToSingle(BitConverter.GetBytes(l), 0);
Console.WriteLine("-0.0 float: 0x80000000, {0}", f);

Output: 输出:

-0.0 float: 0x80000000, 0

What I'm after is converting the UInt32 pattern of 0x80000000 into the correct value of -0.0f and printing this value as -0.0 – DragonSpit 我要做的是将0x80000000的UInt32模式转换为-0.0f的正确值,并将此值打印为-0.0 – DragonSpit

I have a bad news, apparently there's no way to get what you want: 我有一个坏消息,显然无法获得您想要的东西:

By PETER SESTOFT: Some of the confusion over negative zero may stem from the fact that the current implementations of C# print positive and negative zero in the same way, as 0.0, and no combination of formatting parameters seems to affect that display. PETER SESTOFT:关于负零的某些困惑可能是由于以下事实造成的:当前的C#实现以与0.0相同的方式打印正零和负零,并且似乎没有格式化参数的组合会影响该显示。 Although this is probably done with the best of intentions, it is unfortunate. 尽管这可能是出于最好的意图,但这是不幸的。 To reveal a negative zero, you must resort to strange-looking code like this, which works because 1/(-0.0) = -Infinity < 0: 要显示一个负零,您必须诉诸于看起来很奇怪的代码,该代码之所以起作用,是因为1 /(-0.0)= -Infinity <0:

public static string DoubleToString(double d) {
 if (d == 0.0 && 1/d < 0)
 return "-0.0";
 else
 return d.ToString();
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM