Is it possible to get 0 by subtracting two unequal floating point numbers?

后端 未结 12 1802
余生分开走
余生分开走 2021-01-30 07:50

Is it possible to get division by 0 (or infinity) in the following example?

public double calculation(double a, double          


        
12条回答
  •  借酒劲吻你
    2021-01-30 08:31

    You shouldn't ever compare floats or doubles for equality; because, you can't really guarantee that the number you assign to the float or double is exact.

    To compare floats for equality sanely, you need to check if the value is "close enough" to the same value:

    if ((first >= second - error) || (first <= second + error)
    

提交回复
热议问题