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

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

    Based on @malarres response and @Taemyr comment, here is my little contribution:

    public double calculation(double a, double b)
    {
         double c = 2 / (a - b);
    
         // Should not have a big cost.
         if (isnan(c) || isinf(c))
         {
             return 0; // A 'whatever' value.
         }
         else
         {
             return c;
         }
    }
    

    My point is to says: the easyest way to know if the result of the division is nan or inf is actualy to perform the division.

提交回复
热议问题