Go Down

Topic: multiplication error using long variable (Read 753 times) previous topic - next topic

vorb

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: [Select]

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: [Select]

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; ?

mellis

#1
Mar 08, 2007, 04:35 pm Last Edit: Mar 08, 2007, 04:35 pm by mellis Reason: 1
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: [Select]
product = 1087L * 44L;

vorb

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

Go Up