所以我想知道,如果步长小于 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 运行,但正如您所见,它并没有这样做。我听说使用浮点数作为循环计数器是不安全的,因为浮点数精度不准确。我使用浮点变量作为循环计数器的事实可能是我的问题的原因。那么我的问题有什么解决方案呢?提前感谢您的友好回复!