繁体   English   中英

为什么我的浮点数不打印在 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]);
    }
}

我的 output: 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() function 返回要写入的字符串的长度,因此您可以将其用于分配。

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

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);

撇开数组长度问题不谈,可能导致此问题的是开发环境未启用浮动 printf 支持。 Eclipse 在某些环境中有一个 UI 设置——我在 Simplicity Studio 中看到过。 或者您可以手动添加 linker 选项 -u _printf_float

使用 Eclipse 添加 float printf 支持

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM