【发布时间】:2019-08-05 13:05:45
【问题描述】:
我正在尝试从头开始编写一个 Objective-C(++) 应用程序,但完全不知道为什么在 while 循环中测试 float 似乎会导致无限循环。
首先,文件:test.mm
#include <stdio.h>
#include <mach/mach_time.h>
int main(int argc, const char* argv[])
{
#pragma unused(argc)
#pragma unused(argv)
// --- LOOP ---
float timer = 2.0f;
float debugMarker = 2.0f;
uint64_t lastLoopStart = mach_absolute_time();
mach_timebase_info_data_t timebase;
mach_timebase_info(&timebase);
while(timer > 0.0f)
{
uint64_t now = mach_absolute_time();
uint64_t elapsed = now - lastLoopStart;
uint64_t nanos = elapsed * timebase.numer / timebase.denom;
float deltaTime = static_cast<float>(static_cast<double>(nanos) * 1.0E-9);
timer -= deltaTime;
lastLoopStart = now;
// Including this line avoids the bug
// timer -= 0.1f;
// This does not cause the bug
// if(0.0f < timer)
// This causes the bug
// if(debugMarker > 0.0f)
// This causes the bug
if(debugMarker >= timer)
{
printf("timer: %f\n", static_cast<double>(timer));
debugMarker -= 1.0f;
}
}
printf("DONE\n");
return (0);
}
编译:clang -g -Weverything test.mm
运行此代码生成的程序会导致循环输出一次定时器值,然后出现无限循环。
使用if(debugMarker > 0.0f) 会导致它打印两次计时器值。
我完全不知道这里会发生什么。 任何帮助将不胜感激!
【问题讨论】:
-
浮点精度不足以从 2 秒中减去纳秒。您的代码什么也不做,尤其是当您不打印任何内容时。所以它花了 11-30 纳秒(取决于你的设备)。
标签: objective-c macos clang