3

我正在构建一个应用程序,显示你走了多少英里,我希望它有 3 个小数位。例如,“0.435 英里”。我试过下面的代码:

static char stopwatch_miles[50];
snprintf(stopwatch_miles, sizeof(stopwatch_miles), "%.3f miles", num_miles);
text_layer_set_text(miles_layer, stopwatch_miles);

num_miles是一个计算的浮点变量。但是,Pebblesnprintf在 1.13 中不推荐使用浮点数。有简单的解决方法吗?也许使用int,在我的数学运算之前将其乘以 1000 并在格式中添加小数位?

4

1 回答 1

4

您可以尝试将 'num_miles' 乘以 1000,将其转换为整数,然后将它们显示为常规 int 值

snprintf(stopwatch_miles, sizeof(int), "%d.%d miles", (int)num_miles, (int)(num_miles*1000)%1000);

编辑:Manül 轻轻地提醒我第二个 %d 应该是 %03d 而不是前一个答案。该行应该是:

    snprintf(stopwatch_miles, sizeof(stopwatch_miles), "%d.%03d miles", (int)num_miles, (int)(num_miles*1000)%1000);
于 2014-06-12T15:36:31.813 回答