there solutions problem small numbers:
- here: difference between 2 numbers
- here: c# function find delta of 2 numbers
- here: how can find difference between 2 values in c#?
i'll summarise answer them all:
math.abs(a - b)
the problem when numbers large gives wrong answer (by means of overflow). worse still, if (a - b) = int32.minvalue
math.abs
crashes exception (because int32.maxvalue = int32.minvalue - 1
). specific nature leads difficult-to-reproduce bugs.
maybe i'm missing known library function, there way of determining difference safely?
as suggested others, use biginteger defined in system.numerics (you'll have include namespace in visual studio) can do:
biginteger = new biginteger(); biginteger b = new biginteger(); // assign values , b somewhere in here... // use included biginteger.abs method biginteger result = biginteger.abs(a - b);
jeremy thompson's answer still valid, note biginteger namespace includes absolute value method, there shouldn't need special logic. also, math.abs expects decimal, give grief if try pass in biginteger.
keep in mind there caveats using bigintegers. if have ludicrously large number, c# try allocate memory it, , may run out of memory exceptions. on flip side, bigintegers great because amount of memory allotted them dynamically changed number gets larger.
check out microsoft reference here more info: https://msdn.microsoft.com/en-us/library/system.numerics.biginteger(v=vs.110).aspx
Comments
Post a Comment