右圆环
我必须以步骤 0.5 从 0 循环到 5。但当值为 5 时,循环应该相反。
bool forward = true;
int counter = 0;
float val = 5.0f;
// And somewhere in global app cycle:
if (val <= 0.0 && forward) forward = false;
if (forward) val -= .5f;
if (val >= 5.0 && !forward) forward = true;
if (!forward) val += .5f;
但结果有时是负数,我认为,这是一个有点难看的代码。
0.2
0.18
0.16
0.14
0.12
0.1
0.08
0.06
0.04
0.02
2.98023e-08
-0.02
2.98023e-08
0.02
0.04
0.06
0.08
0.1
0.12
0.14
0.16
0.18
0.2
0.2
0.18
I have to cycle from 0 to 5 with step 0.5. But the cycle should be reversed when the value is 5.
bool forward = true;
int counter = 0;
float val = 5.0f;
// And somewhere in global app cycle:
if (val <= 0.0 && forward) forward = false;
if (forward) val -= .5f;
if (val >= 5.0 && !forward) forward = true;
if (!forward) val += .5f;
But the result is sometimes negative numbers and, I think, that's a bit ugly code.
0.2
0.18
0.16
0.14
0.12
0.1
0.08
0.06
0.04
0.02
2.98023e-08
-0.02
2.98023e-08
0.02
0.04
0.06
0.08
0.1
0.12
0.14
0.16
0.18
0.2
0.2
0.18
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您遇到的问题是
0.2
无法精确地用浮点表示。因此,当您编写val -= 0.2
时,您真正做的是val -= 0.20000000298023224;
。因此,您会积累错误。解决方案是不使用浮点来控制循环。请改用
int
,并乘以常量以获得val
。例如:The problem you are experiencing is that
0.2
cannot be exactly represented in floating-point. So when you writeval -= 0.2
, what you're really doing isval -= 0.20000000298023224;
. Therefore, you accumulate errors.The solution is to not use floating-point to control your loop. Use an
int
instead, and multiply by a constant to getval
. e.g.:在步骤 1 中使用从 0 到 10 的整数,或者在步骤 5 中使用从 0 到 50 的整数。浮点数可以是 0.00000012,因此它不小于或等于 0.0。
您可以在需要时根据循环变量计算浮点数。
Use integers for such cycles from 0 to 10 with step 1 or from 0 to 50 with step 5. Float may be 0.00000012 and so it is not less or equal than 0.0.
You can calculate the float from your cycle variable when needed.
|值 - 5.0| < eps && |值 - 0 | < eps 哪里 | |在您的情况下 fabsf() 我想
还请记住,每当减去两个几乎相等(浮点表示)的值时,精度就会有所损失。
|val - 5.0| < eps && |val - 0 | < eps where | | in your case fabsf() i guess
also keep in mind that there is some loss in precision whenever two almost equal (floating point representation) values are subtracted.
可以不指定每次移动的距离,而指定划分的数量吗?
这样,您的值就不会因精度/舍入误差而漂移
例如:
Instead of specifying the distance to move each time, could the number of divisions be specified?
This way, your value won't ever drift due to precision/rounding errors
EG: