Strange results with floating-point comparison

后端 未结 10 1748
余生分开走
余生分开走 2020-12-10 08:34

I have this simple test:

double h;
...
// code that assigns h its initial value, used below
...
if ((h>0) && (h<1)){
 //branch 1 -some computati         


        
10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-10 09:32

    Okay, you've posted the code. You are calculating h by a series of arithmetic operations from what looks like fairly arbitrary numbers. This means you're going to get a very close approximation to the ideal value of h, but not quite the right one.

    This means that you need to do approximate comparisons. Testing (h == 1.0) will succeed only by accident; try (fabs(h - 1.0) < 1e-10) or something like that (using a const double instead of a magic number for tolerance). Make the appropriate changes for other comparisons.

提交回复
热议问题