gpt4 book ai didi

c# - 零有不同的十进制值吗?

转载 作者:行者123 更新时间:2023-11-30 14:05:38 27 4
gpt4 key购买 nike

我正在使用 C# 代码工作,该代码通过以下方式分配十进制值。这些值是相同的还是有区别?

decimal a = 0;
decimal b = 0m;
decimal c = 0.00m;

最佳答案

只是在其他好的答案中添加一点点更实用的信息

小数有许多0的内部表示,但是当比较时它们都将等于

Decimal Struct

The binary representation of a Decimal value consists of a 1-bit sign, a 96-bit integer number, and a scaling factor used to divide the 96-bit integer and specify what portion of it is a decimal fraction. The scaling factor is implicitly the number 10, raised to an exponent ranging from 0 to 28. Therefore, the binary representation of a Decimal value the form, ((-296 to 296) / 10(0 to 28)), where -(296-1) is equal to MinValue, and 296-1 is equal to MaxValue.

The scaling factor also preserves any trailing zeros in a Decimal number. Trailing zeros do not affect the value of a Decimal number in arithmetic or comparison operations. However, trailing zeros might be revealed by the ToString method if an appropriate format string is applied.

改变比例因子的例子

string GetBits(decimal d)
{
var bits = decimal.GetBits(d);
return $"{d==0} {d,31} {bits[3],10:X8}{bits[2],10:X8}{bits[1],10:X8}{bits[0],10:X8}";
}

Console.WriteLine(GetBits(0));
Console.WriteLine(GetBits(0.0m));
Console.WriteLine(GetBits(0.000m));
// Manually set the Scaling Factor and Sign
Console.WriteLine(GetBits(new decimal(0,0,0,true,10)));

输出

Equals 0                    ToString       Other        Hi       Mid        Lo
------------------------------------------------------------------------------
True 0 00000000 00000000 00000000 00000000
True 0.0 00010000 00000000 00000000 00000000
True 0.000 00030000 00000000 00000000 00000000
True 0.0000000000 800A0000 00000000 00000000 00000000

关于c# - 零有不同的十进制值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55464543/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com