浮点值评估完全错误
嘿互联网。我在 C 中遇到一个非常奇怪的问题。我正在导出一个浮点值,然后检查它是否大于 0。但是,即使该值小于零,比较的结果始终为 true。代码如下:
if (sVel > 0.0f)
{
sVel += 1.0f;
sVel -= 1.0f;
NSLog(@"SEP VEL: %1.6f", sVel);
return;
}
因此,将 sVel 设置为 100 会按预期打印日志并命中 return 语句;凉爽的。但是,将 sVel 设置为 -100 不会不打印日志,并且仍然会命中 return 语句。我完全困惑了,我不知道从哪里开始追踪这个......
Hey internets. I am having a VERY strange issue in C. I am deriving a float value, and then checking to see if it is greater than 0. However, the comparison is always evaluating to true, even if the value is less than zero. Here is the code:
if (sVel > 0.0f)
{
sVel += 1.0f;
sVel -= 1.0f;
NSLog(@"SEP VEL: %1.6f", sVel);
return;
}
So, setting sVel to 100 prints the log as expected and hits the return statement; cool. However, setting sVel to -100 does not print the log and still hits the return statement. I am utterly confused and I'm not sure where to start tracking this one down...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来您正在使用调试器跟踪代码。大多数编译器可能会优化代码并执行相同的返回语句。这样看来,无论 sVel 的初始值如何,您都会跳转到返回代码。
真正的证据是 print 语句。由于未打印日志,这意味着 sVel 的评估正确。尝试将日志放在 if 块之外,看看它何时显示。
It looks like you are tracing the code using a debugger. Most compilers will probably optimize the code and the same return statement will be executed. It would appear then, that you are jumping to the return code regardless of the initial value of sVel.
The real proof is the print statement though. Since the log is not printed, that means, sVel was evaluated correctly. Try to put a log outside of the if block and see when it gets displayed.
什么退货声明?如果 sVel 为负数,则不应执行任何操作。失败之后会发生什么?您确定它只是没有从函数返回吗?
What return statement ? If sVel is negative, it should not execute anything. What comes after the fallthrough ? Are you sure its just not returning from the function ?