除以零返回无限



我是编程新手,我有除以零的问题。问题在代码的注释中解释。

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

你不应该返回 0。您应该返回float.NegativeInfinity(如果a为负数)或float.PositiveInfinity(如果a为正数),如果ab均为 0,则应返回float.NaN。请注意,这与在代码中执行此操作时获得的行为相同:

return a / b;

因此,您可能只想将代码更改为:

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

如果除以 0 表示应用程序中的特定非法条件,并且不希望传播float.NaN值,则应引发异常。喜欢:

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

看到这个小提琴,它会返回float.PositiveInfinity.

如果您不喜欢默认值,则由您决定返回什么...通常会抛出异常,但它不是"返回"。

最接近的答案是返回可为空的float? -

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

您也可以考虑double.PositiveInfinity,但处理异常或可为空的类型通常更容易。

注意:由于先前计算中可能存在舍入问题,因此将浮点数与 0 进行比较时要小心(使用 Equals== ) - 像这样将双精度数与 0 进行比较是错误的:doubleVariable==0?

你想要的结果是什么?无限的价值?没有float.如果b为零,则不要调用该方法,除非你想要特定结果。

至于你的代码,你可以这样做(这只是许多解决方案中的一个):使用内置的无穷大常数,如下所示:

public float Divide (float a, float b)
{
    return Equals (b, 0) ? float.NegativeInfinity : a / b;
}

最新更新