【发布时间】:2017-09-19 18:36:49
【问题描述】:
我正在尝试设置一个 nodemcu 模块来从温度传感器收集数据,并使用 mqtt pubsubclient 将其发送到我的 mqtt 代理,但这不是问题。
我正在尝试以只有一位小数的格式发送温度,此时我已成功将其向上或向下舍入,但格式不正确。截至目前,它将温度四舍五入到 24.50、27.80、23.10 等。我想删除尾随的零点,所以它变成 24.5、27.8、23.1 等。
到目前为止,我已经设置了这个代码:
#include <math.h>
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
float temp = 0;
void loop {
float newTemp = sensors.getTempCByIndex(0);
temp = roundf((newTemp * 10)) / 10;
serial.println(String(temp).c_str())
client.publish("/test/temperature", String(temp).c_str(), true);
}
我对 c++ 还很陌生,因此我们将不胜感激。
【问题讨论】:
-
我尝试了正确的答案,但我得到错误“'stringstream' is not declared in this scope” for line
stringstream stream; -
@MikeNakis - 有点重复,但又不是;问题涉及嵌入式系统,有时标准库不完整。
标签: c++ decimal rounding trailing