对于小数,这个问题已经有了解决方案:
- 此处: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
关于c# - 两个大数之间的区别C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38702478/