C++ Arduino sprintf float 未格式化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27651012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:50:31  来源:igfitidea点击:

Arduino sprintf float not formatting

c++arduinoprintf

提问by Mistergreen

I have this arduino sketch,

我有这个 arduino 草图,

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

temperature prints out as

温度打印为

? F

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

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

回答by Dinal24

Due to some performance reasons %fis 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:

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

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

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

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

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.

您可以更改最小宽度和精度以匹配您正在转换的浮点数。

回答by Cameron Lowell Palmer

As has been stated before Float support is not included in sprintfon Arduino.

正如之前所说sprintf,Arduino 中不包含 Float 支持。

String class

字符串类

Arduino has its own Stringclass.

Arduino 有自己的String类。

String value = String(3.14);

then,

然后,

char *result = value.c_str();

String class reference, link above

字符串类参考,上面的链接

Constructs an instance of the String class. There are multiple versions that construct Strings from different data types (i.e. format them as sequences of characters), including:

构造 String 类的实例。有多个版本可以从不同的数据类型构造字符串(即将它们格式化为字符序列),包括:

  • a constant string of characters, in double quotes (i.e. a char array)
  • a single constant character, in single quotes
  • another instance of the String object
  • a constant integer or long integer
  • a constant integer or long integer, using a specified base
  • an integer or long integer variable
  • an integer or long integer variable, using a specified base
  • a float or double, using a specified decimal palces
  • 双引号中的常量字符串(即字符数组)
  • 单个常量字符,在单引号中
  • String 对象的另一个实例
  • 常量整数或长整数
  • 使用指定基数的常量整数或长整数
  • 整数或长整数变量
  • 整数或长整数变量,使用指定的基数
  • 浮点数或双精度数,使用指定的十进制数

回答by Helmut Wunder

dtostrf()is deprecated, and it doesn't exist on every board core platforms. On the other hand, sprintf()doesn't format floats on AVR platforms!

dtostrf()已弃用,并且并非在每个主板核心平台上都存在。另一方面,sprintf()不会在 AVR 平台上格式化浮动!