Go Down

Topic: 1000 * 150 = 18928 ?!? (Read 694 times) previous topic - next topic


Am I just insane?

Code: [Select]
Serial.println(1000 * 150);
 Serial.println(E12[i-1] * multiply_factor);

I'm trying to work out why I'm getting unexpected values, the second line should be identical to the top line, and the result is the same, but for the life of me, I cannot see what the heck is going on...



1000 is an integer. 150 is an integer. 150,000 is NOT an integer.

The compiler is using integer arithmetic with integer variables, expecting an integer result, which is not what you get, given the actual inputs.

The types of E12 and multiply_factor are unknown, so I can not tell you why that works.
The art of getting good answers lies in asking good questions.


Remember integers are 16-bit numbers thus lie in the range -32768 to 32767. You have 1000*150=150000 which is bigger than 32767. Now if you subtract out 65536 (2**16) you get 150000-65536 = 86646. Still too big. Do it again: 86646-65536=18928. Ta da!

If you want to do 32-bit arithmetic to get a 32-bit result:

Code: [Select]
Serial.println(1000L * 150L);

The Quick Shield: breakout all 28 pins to quick-connect terminals


Nov 15, 2010, 08:37 am Last Edit: Nov 15, 2010, 08:44 am by AWOL Reason: 1
1000 is an integer. 150 is an integer. 150,000 is NOT an integer.

What he meant to say was:
"On an Arduino, 1000 is an "int". "150" is an "int". 150,000 is NOT an "int"."

Clearly, all are integers.

"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Go Up