Search code examples
c#divide-by-zero

Divide by zero return infinite


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?
}

Solution

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