I am trying to use simple multiplication . But it gives me a negative (-21680) result. I am getting angry. WHY?
Someone explain me it
long raw;
int a = 255;
int b = 1200;
void setup() {
Serial.begin(9600);
}
void loop() {
raw = a*b;
Serial.print("Raw");
Serial.print(" ");
Serial.print(raw);
Serial.print(" ");
Serial.println();
Serial.println();
}
What is 255 * 1200?
What is the largest value that will fit in an int? (Hint: much much less than the result of that multiplication.)
Use long instead of int.
I used even a simple numbers like raw = 255 * 1200;
But result is same. I need this multiplication in another sketch. But seems it is not working or my brain stoped work >:(
Try
raw = a * (long)b;
to stop the compiler producing an int output.
UKHeliBob:
Try
raw = a * (long)b;
to stop the compiler producing an int output.
AWOL:
raw = 255L * 1200L;
Thank You! Both of these are working.
Deep_Sky:
I used even a simple numbers like raw = 255 * 1200;
But result is same. I need this multiplication in another sketch. But seems it is not working or my brain stoped work >:(
Because all numbers are considered as int unless they are too big or you specify otherwise. An int times an int is an int so this still overflows. It does not matter the type you wish to store the result in, that happens after the math has already overflowed.