Multiplying two positive Int32 returns incorrect, negative answer?

廉价感情. 提交于 2019-11-29 12:10:37

The numbers are probably large enough to overflow Int32.MaxValue.

Consider:

var r = Int32.MaxValue / 2;     // r = 1073741823
var ans = r * 3;                // ans = -1073741827

The reason for this is that negative integers are represented with a 1 in the largest bit, so any multiplication which is larger than the maximum value will have a 1 in this position, which is interpreted as a negative value.

Overflow is a danger with all integral types (int, short, byte, sbyte, char, long, ulong, ushort, and uint). You could use a floating point type, like float or double, but this comes with other problems, like rounding and equality issues. You have to know what kind of numbers you expect, then you might use other types like long, uint, ulong or a floating point type like double or decimal. Ultimately, if you don't know what could happen, you need to write guard code on the input (e.g. wrap it in a checked { } block [thanks, @EricLippert]), and handle it when it is a value outside the range you've designed for.

EDIT: Another option in .Net 4.0+ is to use System.Numerics.BigInteger, which avoids any overflow, but can be slow.

The quick and dirty solution is just to cast one of the values to a long and then cast the result back to int, if possible.

Edit: There is no need to use BigInteger for this case as int x int can never overflow a long.

Its probably a Integer overflow exception. It can occur even if you are storing the number in a variable that is big enough. Example(long,double etc)

int one = int.MaxValue;
int two = int.MaxValue;

long sum = (long)(one + two); //Returns -2, because the cast was after the sum
                             //(long) -2.

You can cast them before the sum and get the correct result

int one = int.MaxValue;
int two = int.MaxValue;

long sum = (long) one + (long)two; //Returns 4294967294, it casts both the 
                                   //integer to long and then adds them 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!