【发布时间】:2020-07-17 23:03:48
【问题描述】:
我的花车没有打印到 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(temp)是错误的,因为temp不是字符串。你如何打印整数? -
我很惊讶这段代码没有崩溃。
-
检查您的手册。某些嵌入式环境不支持打印浮点数。
-
@PurpleSpark 您将
int或float传递给需要char *的函数。实际上,这段代码甚至不应该编译。 -
u8_t buf[strlen("temp (K): %.2f\n") + strlen(temp)];这一行在很多层面上都是错误的。不要使用sprintf,最好使用snprintf。你在什么平台上编程?您使用的是什么编译器、编译器选项和编译器版本?如果你在一些裸机目标上编程,很可能你正在使用 newlib 而没有使用-uprintf_float(或类似的东西)。