Closed ruggi99 closed 7 years ago
Really? What did you test the code on? The default data type in C++ is always an integer. The size depends on the machine (e.g. 16 bit vs. 32 bit) but it's never a double. I ran the code below with the indicated results.
// testing dec2bcd
// j.christensen 11jan2017
// running on an arduino uno, this returns:
// 100
// 100
// 64
// 64
uint8_t dec2bcd1(uint8_t n) { return n + 6 * (n / 10); }
uint8_t dec2bcd2(uint8_t n) { return n + 6 * floor(n / 10); }
void setup(void)
{
Serial.begin(9600);
Serial.println(dec2bcd1(64));
Serial.println(dec2bcd2(64));
Serial.println(dec2bcd1(64), HEX);
Serial.println(dec2bcd2(64), HEX);
}
void loop(void)
{
}
In my opinion, the function:
should be written as:
because (n / 10) is double in c++, and when it's multiplicated by 6 it gives wrong results. Example: dec2bcd(64) returns 102 instead of 100.