Pages: [1]   Go Down
Author Topic: multiplication error using long variable  (Read 693 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 13
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I have a variable that is sometimes greater than 32,767 so I can't use int type. Instead I use long, but I get a strange error when multiplying with the long variable.

For example, my variable is called 'product' and at some point I set product = 1087 * 44. I expect to get product = 47828 from this but instead I get product =-17708!

What is going on here?

Here is a sample code that shows the problem I'm encountering:
Code:
long product = 0;

void setup(){
     Serial.begin(9600);
}

void loop(){
     product = 1087*44; //this should return 47828 but instead it returns -17708
     Serial.print("1087 * 44 = ");
     Serial.println(product);
     delay(5000);
}

If I do it this way I get the correct result however:
Code:
long product = 0;

void setup(){
     Serial.begin(9600);
}

void loop(){
     product = 1087;
     Serial.print(product);
     Serial.print(" * ");
     Serial.print(44);
     product=product*44;
     Serial.print(" = ");
     Serial.println(product);
     delay(5000);
}

Am I just using incorrect syntax when I write product=1087*44; ?
Logged

Forum Administrator
Cambridge, MA
Offline Offline
Faraday Member
*****
Karma: 12
Posts: 3538
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

The problem is that both 1087 and 44 are integers, so the multiplication is done with integers (which only go up to 32,767), then the result (-17708) is stored in the long.  To get around this, you can declare the integer constants as longs by appending an L, e.g.:

Code:
product = 1087L * 44L;
« Last Edit: March 08, 2007, 10:35:48 am by mellis » Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 13
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Oh I never thought it would do that.
Thank you.
Logged

Pages: [1]   Go Up
Jump to: