Pages: [1]   Go Down
 Author Topic: 1000 * 150 = 18928 ?!?  (Read 251 times) 0 Members and 1 Guest are viewing this topic.
Southern Ontario
Offline
Sr. Member
Karma: 2
Posts: 279
Arduino rocks
 « on: November 14, 2010, 06:52:30 pm » Bigger Smaller 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
Brattain Member
Karma: 336
Posts: 36476
Seattle, WA USA
 « Reply #1 on: November 14, 2010, 06:57:04 pm » Bigger Smaller 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
Karma: 12
Posts: 2857
ruggedcircuits.com
 « Reply #2 on: November 14, 2010, 07:35:21 pm » Bigger Smaller 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
Online
Brattain Member
Karma: 143
Posts: 19379
I don't think you connected the grounds, Dave.
 « Reply #3 on: November 15, 2010, 02:37:12 am » Bigger Smaller 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.

 Pages: [1]   Go Up