I have some expressions in my code to control motor response settings. For some odd reason I'm getting a weird result when I use parenthesis. I've tried using different variable types in case the problem is with roll-over. The problem only seem to go away when I rewrite the expression without the parenthesis. Any help with this issue would be greatly appreciated as there are quite a few expressions in my motor control code I'd have to reformat! The following is an example of one of the expressions I'm being troubled by.
void loop() {
static unsigned long tSerial = 0;
int ansInt = 0;
long ansLong = 0;
double ansDouble = 0;
int ans2Int = 0;
int a = 48;
int b = 99;
int c = 100;
Expression 1 stored as int: 3647
Expression 1 stored as long: 3647
Expression 1 stored as double: 3647.00
Expression 2 stored as int: 126
E6 has been defined as 1000000
jremington - your observation is correct. I changed the three variables a,b,c to long and got the correct solution. Any reason these variables are driving the variable type for the parenthesis and not ans?
The problem is integer overflow. This (abc) is a product of "int" whose result is defined to be "int".
4899100 = 475,200. The result will be truncated to 16 bits (the size of an int on the 386-based Arduinos). 475,200 = 74040(hex). Truncate to 16-bits is 4040(hex) and convert back to decimal is 16448.
60000000/16448 = 3647.86 which is where the 3647 result comes from.
With /a/b/c, the divisions are done one at a time and involve a long integer being divided by an int. The division will produce the correct result because the intermediate results are long integers.
The reason I asked the question about the product of a, b and c in reply #3 was to prompt you to find out by printing it, then you would have seen the problem immediately.
Don't worry AWOL. As soon as jremington suggested the int issue I casted 'a' to long and re-ran. I get it now. Thanks for the help - I thought I was going crazy! lol