0

使用 round() 时出现意外结果:

#include <Arduino.h>
int main(void) {
  init();
  Serial.begin(9600);
  float a = 1.0;
  float b = round(a);
  Serial.println(b);  // prints "1.50" 
  delay(100);
  return 0;
}

获得期望值的诀窍是什么1.0

4

1 回答 1

1

看来我发现了问题:问题是由round()Arduino.h 中的宏引起的:

#define round(x)     ({ typeof (x) _x = (x); _x >= 0 ? (long)_x + 0.5 : (long)_x - 0.5; })

您必须将round()结果转换为整数类型才能获得预期的浮点数:

float a = 1.0f;
float b = (int16_t) round(a);
Serial.println(b);  // "1.00"
于 2021-02-16T22:23:55.823 回答