问题
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