在 ATMega328P 的 Arduino IDE 中 round() 结果错误

问题描述

使用 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 的技巧是什么?

解决方法

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

#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"