Domanda

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.

È stato utile?

Soluzione

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.

Altri suggerimenti

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).

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top