2

I'm new to programming and I have a problem with dividing by zero. Problem is explained in comment in code.

public float Divide (float a, float b)
{
    if (!Equals (b, 0))
        return a / b;
    else
        return 0; // what should this return contains not to giving me back  infinite?
                  // But for example message that you can't divide by zero?
}
Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62
Honza Kubiš
  • 63
  • 1
  • 4
  • Whatever you want. Are you asking for exceptions? – SLaks Apr 29 '15 at 23:28
  • 2
    Unrelated note: you should be careful comparing float numbers for equality. Generally, you should never do it, as it is very likely to backfire due to precision issues. – n0rd Apr 29 '15 at 23:44

3 Answers3

7

You should not be returning 0. You should return float.NegativeInfinity (if a is negative) or float.PositiveInfinity (if a is positive), and float.NaN if both a and b are 0. Note that this is the same behavior that you would get if you did this in your code:

return a / b;

So you might want to simply change your code to read:

public float podil (float a, float b) {
    return a / b;
}

If dividing by 0 represents a specific illegal condition in your application, and you don't want float.NaN values to propagate, you should throw an exception. Like:

public float podil (float a, float b) {
    var result = a / b;
    if (float.IsNan(result))
        throw new DivideByZeroException(); // or a different exception type.
    return result;
}

See this fiddle, It will return float.PositiveInfinity.

Alex
  • 13,024
  • 33
  • 62
  • I'm pretty sure it will throw a `DivideByZero` exception, not return postive/negative infinity – BradleyDotNET Apr 29 '15 at 23:33
  • 4
    @BradleyDotNET not for floats; they will return infinity for division by zero (or NaN for 0/0). Integer division will throw a divide by zero exception. – Erik Apr 29 '15 at 23:36
1

It is up to you what to return if you don't like default... Usually one would throw exception, but it is not "return".

Most close answer would be return nullable float? -

public float? podil (float a, float b) 
{
    return b == 0 ? (float?) null : a / b;
}

You may also consider double.PositiveInfinity, but dealing with exceptions or nullable types is generally easier.

Note: be careful with comparing floating point numbers to 0 (either with Equals or ==) due to possible rounding issues in previous computations - Is it wrong to compare a double to 0 like this: doubleVariable==0?)

Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
0

What is the result you want? An infinite value? There is none for float.Don't call the method if b is zero unless you want a specific result.

As for your code you could to this (it's just one solution of many): use the built-in infinity constant such as this:

public float Divide (float a, float b)
{
    return Equals (b, 0) ? float.NegativeInfinity : a / b;
}
Quality Catalyst
  • 6,531
  • 8
  • 38
  • 62