两个大数C#的区别 [英] Difference between two large numbers C#

查看:238
本文介绍了两个大数C#的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有已经对这个问题的解决方案的小的数字

There are already solutions to this problem for small numbers:

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

我要总结的答案他们都:

I'll summarise the answer to them all:

Math.Abs(a - b)

问题是的当数大这给了错误的答案(由溢流的方式)。更糟糕的是,如果(A - B)= Int32.MinValue 然后 Math.Abs​​ 用一个异常崩溃(因为 Int32.MaxValue = Int32.MinValue - 1 )。其具体性质导致难以重现bug。

The problem is when the numbers are large this gives the wrong answer (by means of an overflow). Worse still, if (a - b) = Int32.MinValue then Math.Abs crashes with an exception (because Int32.MaxValue = Int32.MinValue - 1). Its specific nature leads to difficult-to-reproduce bugs.

也许我错过了一些知名的库函数,但有确定安全的区别什么办法?

Maybe I'm missing some well known library function, but is there any way of determining the difference safely?

推荐答案

的建议被他人使用的BigInteger作为System.Numerics定义(你必须包括Visual Studio中的命名空间)
然后,你可以这样做:

As suggested by others, use BigInteger as defined in System.Numerics (you'll have to include the namespace in Visual Studio) Then you can just do:

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);



杰里米·汤普森的答案仍然是有效的,但要注意的BigInteger命名空间包含一个绝对值方法,所以有不应该需要任何特殊的逻辑。此外,Math.Abs​​预计小数,所以它会给你悲伤,如果你尝试在一个BigInteger通过。

Jeremy Thompson's answer is still valid, but note that the BigInteger namespace includes an absolute value method, so there shouldn't be any need for special logic. Also, Math.Abs expects a decimal, so it will give you grief if you try to pass in a BigInteger.

请记住有警告使用BigIntegers。如果你有一个可笑大量,C#将尝试为它分配内存,你可能会遇到内存不足异常。在另一面,BigIntegers是伟大的,因为内存分配给他们的金额是动态变化的数字变大。

Keep in mind there are caveats to using BigIntegers. If you have a ludicrously large number, C# will try to allocate memory for it, and you may run into out of memory exceptions. On the flip side, BigIntegers are great because the amount of memory allotted to them is dynamically changed as the number gets larger.

下面看看微软参考更多信息:的 https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v = vs.110)的.aspx

Check out the microsoft reference here for more info: https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx

这篇关于两个大数C#的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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