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