Arduino的sprintf的漂浮在格式化 [英] Arduino sprintf float not formatting

查看:4834
本文介绍了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风格的字符串,然后用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);

您可以更改最小宽度和precision匹配要转换的浮动。

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

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

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