Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(int) Math.Pow(10, 0) returning zero rather than one

Tags:

c#

algorithm

I'm attempting to reverse an integer and for some reason I receive a RunTime error saying "System.DivideByZeroException: Attempted to divide by zero." Having figured out that Math.Pow returns a double, why doesn't the conversion to an int maintain the result of "1". 10 to the 0 is 1, and 1 converting to 1 should still be 1 even if you include any rounding. Anybody have a good explanation for this?

if (x > 0)
        {
            var i = 0;
            while (x > 0)
            {
                int endDig = x % (10 * ((int)Math.Pow(10, i)));
                myNum += endDig.ToString();
                i += 1;
            }
            int newNum = Int32.Parse(myNum);
            return newNum;
        }
like image 706
springathing Avatar asked May 31 '26 06:05

springathing


2 Answers

The reason of divide by zero here is not really related to truncating result when casting Math.Pow(x, 0) to int. Math.Pow(x, 0) will always return 1, and casting it to int will give you 1. Reason is integer overflow. For example consider:

var pow = (int)Math.Pow(10, 10);

10^10 does not fit into int size, so it will overflow (multiple times), and variable pow will have value -2147483648. When you multiply that by 10, it again overflows and result is 0. At this point you get your divide by zero exception.

To avoid such bizzare results you might want to do arithmetic operations that might unexpectedly result in overflow in checked context:

checked {
    var pow = (int) Math.Pow(10,10); 
    // throws overflow exception so you can fix your buggy code early
}

Of course at that point you already realize that your algorithm to reverse number is not a good one, so refer to another answer for a better way.

like image 178
Evk Avatar answered Jun 01 '26 18:06

Evk


You are encountering limitations of computer-based arithmetic. (Another answer shows the details which I were incorrect in previous versions of my answer.) To avoid these details entirely, you can divide by 10 at the end of each iteration of the loop:

while (x > 0)
{
    int endDig = x % 10;
    //...
    x /= 10;
}

Now you no longer need to worry the limits of int because your number will never be larger than the original input.

like image 28
Code-Apprentice Avatar answered Jun 01 '26 20:06

Code-Apprentice



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!