【问题标题】:How to display a float on the Pebble如何在 Pebble 上显示浮动
【发布时间】:2014-06-12 15:30:36
【问题描述】:

我正在构建一个应用程序来显示您已经走了多少英里,我希望它有 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 是一个计算的浮点变量。但是,Pebble 在 1.13 中不推荐使用 snprintf 中的浮点数。有简单的解决方法吗?也许使用int,在我的数学运算前将其乘以 1000 并在格式中添加小数位?

【问题讨论】:

    标签: c pebble-sdk


    【解决方案1】:

    您可以尝试将 '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);
    

    【讨论】:

    • 第二个 %d 应该是 %03d 以处理例如 0.043 英里
    • 我无法让它正常工作。我要做的是在不同的函数中做完全相同的事情,使用 2 个整数,一个用于前周期,一个用于周期后,并将整个事情作为一个整数而不是浮点数来做。感谢您为我指明正确的方向。
    • sizeof(int) 在这里是错误的。大小必须为stopwatch_miles
    • @JaretBurkett,这正是上面的代码应该做的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2017-01-24
    相关资源
    最近更新 更多