Divide by zero prevention

后端 未结 3 972
攒了一身酷
攒了一身酷 2020-12-11 16:58

What is 1.#INF and why does casting to a float or double prevent a division by 0 of crashing?
Also, any great ideas of how to pre

3条回答
  •  我在风中等你
    2020-12-11 17:27

    1.#INF is positive infinity. You will get it when you divide a positive float by zero (if you divide the float zero itself by zero, then the result will be "not a number").

    On the other hand, if you divide an integer by zero, the program will crash.

    The reason float fZero = 2 / nQuota; crashes is because both operands of the / operator are integers, so the division is performed on integers. It doesn't matter that you then store the result in a float; C++ has no notion of target typing.

    Why positive infinity cast to an integer is the smallest integer, I have no idea.

提交回复
热议问题