两个大数字C#之间的差异

对于小数字,已经有解决这个问题的方法:

>这里:Difference between 2 numbers
>这里:C# function to find the delta of two numbers
>这里:How can I find the difference between 2 values in C#?

我将总结所有人的答案:

Math.Abs(a - b)

问题是当数字很大时,这给出了错误的答案(通过溢出).更糟糕的是,如果(a – b)= Int32.MinValue,则Math.Abs​​会因异常而崩溃(因为Int32.MaxValue = Int32.MinValue – 1):

System.OverflowException occurred
HResult=0x80131516
Message=Negating the minimum value of a twos complement number is
invalid.
Source=mscorlib
StackTrace: at
System.Math.AbsHelper(Int32 value) at System.Math.Abs(Int32 value)

它的特殊性质导致难以重现的错误.

也许我错过了一些众所周知的库函数,但有没有办法安全地确定差异?

解决方法:

正如其他人所建议的那样,使用System.Numerics中定义的BigInteger(您必须在Visual Studio中包含命名空间)
然后你可以这样做:

BigInteger a = new BigInteger();
BigInteger b = new BigInteger();
// Assign values to a and b somewhere in here...
// Then just use included BigInteger.Abs method
BigInteger result = BigInteger.Abs(a - b);

Jeremy Thompson的答案仍然有效,但请注意BigInteger命名空间包含绝对值方法,因此不需要特殊逻辑.此外,Math.Abs​​需要一个小数,所以如果你尝试传入一个BigInteger,它会让你感到悲伤.

请记住,使用BigIntegers时需要注意.如果你有一个非常大的数字,C#将尝试为它分配内存,你可能会遇到内存不足的异常.另一方面,BigIntegers很棒,因为分配给它们的内存量随着数量的增加而动态变化.

有关详细信息,请查看此处的microsoft参考:https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx

上一篇:python – 计算DataFrame Pandas中’times’行之间的差异


下一篇:以周计算日期差异(Javascript)