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

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

    Division by zero is undefined, since the limit from positive numbers tend to infinity, the limited from negative numbers tend to negative infinity.

    Not sure if this is C++ or Java since there is no language tag.

    double calculation(double a, double b)
    {
         if (a == b)
         {
             return nan(""); // C++
    
             return Double.NaN; // Java
         }
         else
         {
             return 2 / (a - b);
         }
    }
    

提交回复
热议问题