步骤小于1的C循环

时间:2015-10-06 09:40:28

标签: loops for-loop floating-accuracy loop-counter

所以我想知道,如果步长小于1,我如何确保循环中的所有步骤都执行?以此循环为例:

for (float y, x = -1.0; x <= 1.0; x += 0.1) {         
    y = (4*x*x*x) + (3*x*x) + (5*x) - 10;
    printf("x = %.2f, y = %.2f\n", x, y);

}

输出:

x = -1.00, y = -16.00
x = -0.90, y = -14.99
x = -0.80, y = -14.13
x = -0.70, y = -13.40
x = -0.60, y = -12.78
x = -0.50, y = -12.25
x = -0.40, y = -11.78
x = -0.30, y = -11.34
x = -0.20, y = -10.91
x = -0.10, y = -10.47
x = 0.00, y = -10.00
x = 0.10, y = -9.47
x = 0.20, y = -8.85
x = 0.30, y = -8.12
x = 0.40, y = -7.26
x = 0.50, y = -6.25
x = 0.60, y = -5.06
x = 0.70, y = -3.66
x = 0.80, y = -2.03
x = 0.90, y = -0.15

我打算循环也运行x = 1,但你可以看到它没有那样做。我听说使用浮点数作为循环计数器是不安全的,因为浮点精度不准确。我使用float变量作为循环计数器的事实可能是我的问题的原因。那么我的问题有什么解决方案?提前感谢您的回复!

1 个答案:

答案 0 :(得分:1)

正如您所指出的,问题是您不应将浮点数用作循环计数器。所以将所有内容乘以10并使用整数:

for (int x = -10; x <= 10; ++x) {
  float y = (0.004*x*x*x) + (0.03*x*x) + (0.5*x) - 10;
  printf("x = %.2f, y = %.2f\n", 0.1*x, y);  
}

产地:

x = -1.00, y = -16.00
x = -0.90, y = -14.99
x = -0.80, y = -14.13
...
x = 0.90, y = -0.15
x = 1.00, y = 2.00

正如所料。

或许更好:逻辑上将你的循环变量与有意义的东西分开。

 for(int i = -10; i <= 10; ++i) {
    float x = 0.1 * i;
    float y = (4*x*x*x) + (3*x*x) + (5*x) - 10;
    printf("x = %.2f, y = %.2f\n", x, y);    
}