Possible Duplicate:
Why “for( i = 0.1 ; i != 1.0 ; i += 0.1)” doesn’t break at i = 1.0?
我有一个数字(实数)区间[x,y]。我必须用类似的方法来迭代它:

nr = 0;
for (i = x; i <= y; i += step) //step is a small double value
    nr++;

对于0.001步的[-1,1],nr显然应该是2001(-1.000。。。0.999 1.000),但它计算nr=2000(我调查过,但最后一次比较失败:0.999+0.001>1.000)
我如何计算准确的nr值?

最佳答案

int nsteps = (int)((y-x)/step);
for(int i=0; nsteps; ++i){
   double v = x + (i*step);  // use v in your calculations
}

关于c - c中的 double 比较失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13751639/

10-11 22:01
查看更多