Arduino sprintf 浮点数未格式化 [英] Arduino sprintf float not formatting

查看:33
本文介绍了Arduino sprintf 浮点数未格式化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个 arduino 草图,

I have this arduino sketch,

char temperature[10];
float temp = 10.55;
sprintf(temperature,"%f F", temp);
Serial.println(temperature);

温度打印为

? F

关于如何格式化这个浮点数的任何想法?我需要它是一个字符字符串.

Any thoughts on how to format this float? I need it to be a char string.

推荐答案

由于某些性能原因,%f 未包含在 Arduino 的 sprintf() 实现中.更好的选择是使用 dtostrf() - 您将浮点值转换为 C 样式字符串,方法签名如下所示:

Due to some performance reasons %f is not included in the Arduino's implementation of sprintf(). A better option would be to use dtostrf() - you convert the floating point value to a C-style string, Method signature looks like:

char *dtostrf(double val, signed char width, unsigned char prec, char *s)

使用此方法将其转换为C-Style字符串,然后使用sprintf,例如:

Use this method to convert it to a C-Style string and then use sprintf, eg:

char str_temp[6];

/* 4 is mininum width, 2 is precision; float value is copied onto str_temp*/
dtostrf(temp, 4, 2, str_temp);
sprintf(temperature,"%s F", str_temp);

您可以更改最小宽度和精度以匹配您要转换的浮点数.

You can change the minimum width and precision to match the float you are converting.

这篇关于Arduino sprintf 浮点数未格式化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆