2

I wrote a simple divide function in C#:

    private string divide(int a, int b)
    {
        return string.Format("Result: {0}", a / b);
    }

Calling MessageBox.Show(divide(3, 0)) results in, as you would expect, a DivideByZeroException.

So I decided to typecast a into a float (to get a non-whole-number return value), like so:

    private string divide(int a, int b)
    {
        return string.Format("Result: {0}", (float)a / b);
    }

Oddly enough, this now shows me Result: Infinity.

This seems like a bug to me, although I could be mistaken. Is it because the result is now a float, and it's seen as essentially the return value of 3 / 1 x 10^-99999 or something similar?

I'm quite flabbergasted at this result.

ashes999
  • 9,925
  • 16
  • 73
  • 124
  • possible duplicate of [Division by zero: int vs. float](http://stackoverflow.com/questions/4480020/division-by-zero-int-vs-float) – Daniel A. White Oct 17 '11 at 13:22
  • float never throws an exception when dividing by zero. see http://stackoverflow.com/questions/4262286/why-does-c-sharp-allow-dividing-a-non-zero-number-by-zero-in-floating-point-type – Alex Oct 17 '11 at 13:24
  • 1
    I'll add that using doubles wouldn't have changed anything! (technically you would have received `Double.PositiveInfinity` instead of `Single.PositiveInfinity`) – xanatos Oct 17 '11 at 13:32

3 Answers3

3

This is the behavior when you convert int to float. This has been taken from the MSDN documentation:

Dividing a floating-point value by zero will result in either positive infinity, negative infinity, or Not-a-Number (NaN) according to the rules of IEEE 754 arithmetic. Floating-point operations never throw an exception. For more information, see Single and Double.

Daniel Peñalba
  • 30,507
  • 32
  • 137
  • 219
2

From MSDN under the Arithmetic Overflow section:

Floating-point arithmetic overflow or division by zero never throws an exception, because floating-point types are based on IEEE 754 and so have provisions for representing infinity and NaN (Not a Number).

Michael Goldshteyn
  • 71,784
  • 24
  • 131
  • 181
1

No, for float operations that is correct.

The IEEE floating-point standard, supported by almost all modern floating-point units, specifies that every floating point arithmetic operation, including division by zero, has a well-defined result. The standard supports signed zero, as well as infinity and NaN (not a number). There are two zeroes, +0 (positive zero) and −0 (negative zero) and this removes any ambiguity when dividing. In IEEE 754 arithmetic, a ÷ +0 is positive infinity when a is positive, negative infinity when a is negative, and NaN when a = ±0. The infinity signs change when dividing by −0 instead.

Reference

Community
  • 1
  • 1
vcsjones
  • 138,677
  • 31
  • 291
  • 286