Arduino Math Error

Dear All Have a nice day

This is my program in Arduino

long r;
void setup() {
  Serial.begin(9600);
}
void loop() {
  r = 1200 * 50;
  Serial.println(r);
  delay(1000);
}

Result in serial monitor
image

But it should be

1200 x 50 = 60,000

please advice

The term on the right hand side is evaluated by the compiler as a signed 2 byte integer value. This leads to an overflow.

If you write an "L" after one of the two factors the compiler knows that the calculation shall be done using the type "long".

UL -> Unsigned long

  r = 1200 * 50L;

Alternatively cast one of the factors as long():

  r = long(1200) * 50;

On the Arduino Uno (and other ATmega based boards) an int stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1). On the Arduino Due and SAMD based boards (like MKR1000 and Zero), an int stores a 32-bit (4-byte) value. This yields a range of -2,147,483,648 to 2,147,483,647 (minimum value of -2^31 and a maximum value of (2^31) - 1).

See here https://www.arduino.cc/reference/en/language/variables/data-types/int/

And regarding the U, L, UL read here
https://www.arduino.cc/reference/en/language/variables/constants/integerconstants/

2 Likes

Grate Thanks problem solved

Nice, please mark the thread as solved to save other members time :wink:

(Just saw it's done, thanks!)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.