C# Multiplying two variables of value int.MaxValue does not result in OverflowException

旧街凉风 提交于 2019-12-22 10:34:11

问题


I've got an integer array that contains two values, each the maximum value of int32:

int[] factors = new int[] { 2147483647, 2147483647 };

I'm trying to get the product of these two numbers to create an OverflowException:

try
{
    int product = factors[0] * factors [1];
}
catch(Exception ex)
{
}

Much to my surprise (and dismay), product actually returns a value of 1. Why is this, and how would I go about throwing an exception when the product of two integers exceeds int.MaxValue?


回答1:


Because the default behavior of C# is not to check overflow with int. However, you can force overflow checking by using checked keyword.

try
{
    checked
    {
        int product = factors[0] * factors [1];
    }
}
catch(Exception ex)
{
}



回答2:


You will have to call BigMul of the math class(used to multiply large integers and avoid overflow),or else even without exception,by using the * operator will result in 1.

long product = Math.BigMul(factors[0], factors[1]);

to throw the exception you will have to place checked.

checked
{
     int product = factors[0] * factors[1];
}

great tutorial about overflow by using the checked and unchecked

http://www.codeproject.com/Articles/7776/Arithmetic-Overflow-Checking-using-checked-uncheck




回答3:


You need to enclose it in a checked block to throw an overflow exception. Replace int product = factors[0] * factors [1]; with this:

checked
{
    int product = factors[0] * factors [1];
}

Without the checked block the result will be truncated since it exceeds int's maximum capacity.



来源:https://stackoverflow.com/questions/17775846/c-sharp-multiplying-two-variables-of-value-int-maxvalue-does-not-result-in-overf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!