Pages: [1]   Go Down
Author Topic: 1000 * 150 = 18928 ?!?  (Read 462 times)
0 Members and 1 Guest are viewing this topic.
Southern Ontario
Offline Offline
Sr. Member
****
Karma: 2
Posts: 279
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Am I just insane?

Code:
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...

Help!
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 614
Posts: 49343
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

0
Offline Offline
Faraday Member
**
Karma: 16
Posts: 2855
ruggedcircuits.com
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
Serial.println(1000L * 150L);

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

Global Moderator
UK
Offline Offline
Brattain Member
*****
Karma: 302
Posts: 26293
I don't think you connected the grounds, Dave.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
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.

« Last Edit: November 15, 2010, 02:44:46 am by AWOL » Logged

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

Pages: [1]   Go Up
Jump to: