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

后端 未结 12 1814
余生分开走
余生分开走 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:30

    As a workaround, what about the following?

    public double calculation(double a, double b) {
         double c = a - b;
         if (c == 0)
         {
             return 0;
         }
         else
         {
             return 2 / c;
         }
    }
    

    That way you don't depend on IEEE support in any language.

提交回复
热议问题