When a float variable goes out of the float limits, what happens?

后端 未结 2 1687
走了就别回头了
走了就别回头了 2020-12-01 21:17

I remarked two things:

  1. std::numeric_limits::max()+(a small number) gives: std::numeric_limits:

2条回答
  •  -上瘾入骨i
    2020-12-01 21:40

    Formally, the behavior is undefined. On a machine with IEEE floating point, however, overflow after rounding will result in Inf. The precision is limited, however, and the results after rounding of FLT_MAX + 1 are FLT_MAX.

    You can see the same effect with values well under FLT_MAX. Try something like:

    float f1 = 1e20;     // less than FLT_MAX
    float f2 = f1 + 1.0;
    if ( f1 == f2 ) ...
    

    The if will evaluate to true, at least with IEEE arithmetic. (There do exist, or at least have existed, machines where float has enough precision for the if to evaluate to false, but they aren't very common today.)

提交回复
热议问题