I have a sketch that gives the wrong answer to a calculation I need to do.
The calculation it is supposed to do is (abc)/d where a, b, c, d are integers.
For troubleshooting I tried logging the result and substituting the variables with an example of numbers:
Serial.print((9200 * 32)/ 144);
Serial.print(( (float) (9200 * 32)/ (float) 144));
both return 224 instead of 2044, honestly I don't think the casting is necessary but I tried non the less just to be sure.
Someone, please help me
Found out what was the reason, int in arduino is 16 bit, I didn't know
yep and (float) (9200 * 32)
casts the result of 9200*32 into (float) but by then then calculation (and the damage) has been doneSerial.print( (float) 9200 * 32/ 144);
casts 9200 into (float) after which all calculations with it are floating point
1. Your numbers are these integers:
9200; //0x23F0
32; //0x0020
144; //0x0090
You want to operate them this way: (9200*32)/144.
Manual calculation gives: 2044.44.
What result do you expect from MCU -- 2044 or 2044.44?
Serial.print((9200ul*32ul)/144ul); //gives: 2044
Serial.print((float)(9200ul*32ul)/144ul); //gives: 2044.44
The default processing buffer size in Arduino UNO is 16-bit. If there is a number that exceeds the default buffer size (9200*32 = 294400 = 0x47E00), then the user has to make a request to the compiler to enlarge the buffer size (not the data type) as needed through cast -- (unsigned long) 9200 ==> 9200ul.