为什么我的浮点数不是用 C 语言打印的,而我的整数是?

Why are my floats not printing in C but my ints are?

我的浮点数没有打印到 C 中的控制台,我不知道为什么。 ints 打印得很好所以我很困惑为什么浮动。代码如下:

float temp = 9.5;
u8_t buf[strlen("temp (K): %.2f\n") + strlen(temp)];
sprintf(buf, "temp (K): %.2f\n", temp);
cli_output(buf);

cli_output中:

void cli_output(u8_t buf[])
{
    for (int i = 0; i < strlen(buf); i++)
    {
        uart_poll_out(comm_uart, buf[i]);
    }
}

我的输出:Fuel gauge temp (K): 编辑:如果我有下面的代码,它会按预期打印到控制台。

int temp = 9;
u8_t buf[strlen("temp (K): %d\n") + strlen(temp)];
sprintf(buf, "temp (K): %d\n", temp);
cli_output(buf);

strlen() 用于测量字符串的长度,而不是整数或浮点数。

snprintf()函数returns要写入的字符串的长度,所以你可以用它来分配。

另外不要忘记分配终止空字符。

float temp = 9.5;
const char* message = "temp (K): %.2f\n";
int length = snprintf(NULL, 0, message, temp);
u8_t buf[length + 1];
sprintf(buf, message, temp);
cli_output(buf);

撇开数组长度问题不谈,可能导致这种情况的原因是开发环境没有启用 float printf 支持。 Eclipse 在某些环境中对此有一个 UI 设置——我在 Simplicity Studio 中看到过它。或者您可以手动添加链接器选项 -u _printf_float