# 180*2*125/360=4294967239 ?????

//I used arduino 0018
//code:
//---------------------------------------
unsigned long a;

void setup(){
Serial.begin(9600);
a=1802125/360;
}

void loop(){
Serial.println(a);
delay(500);
}
//----------------------------------------
The result should be 125
But now is 4294967239.
why??? Thank you!

``````  a=180*2*125/360;
``````

Actually should = 0.

Why long(0) = -57, i don't know.

Why do you say that?

1802125 = 45000. Ints can hold a maximum of 32767, so you get an overflow into a negative value. Casting the value to a long after all the operations makes no difference, but you then assign that negative number to an unsigned long. Because negative values are stores in two's complement form, their resulting positive interpretation ends up being a very large value. Cast your individual values to unsigned long, then none of your operations will overflow.

[quote author=Tom Carpenter link=topic=117975.msg887984#msg887984 date=1344587400]

``````  a=180*2*125/360;
``````

Actually should = 0.

Why do you say that?

1802125 = 45000. Ints can hold a maximum of 32767, so you get an overflow into a negative value. Casting the value to a long after all the operations makes no difference, but you then assign that negative number to an unsigned long. Because negative values are stores in two's complement form, their resulting positive interpretation ends up being a very large value. Cast your individual values to unsigned long, then none of your operations will overflow.
[/quote]

BIDMAS. It does division first. 125/360 with integer division is 0. Now 125.0/360.0 = some decimal value.

Edit: Never mind, it appears from (C++ Operator Precedence - cppreference.com) that * and / take the same precidence and it works from left to right.

The point in about using L seems to be more likely the cause. I bow out of this thread.

start long arithmetics with 180L * 2 …