hello.
I have an arduino uno platform, and surprisingly it is having problems with simple operations like MULTIPLICATION.
The program should be printing the results of the multiplication of some factors and variables, AND THEY ARE JUST ALL WRONG, because it also prints the value of the variables and they are right, but after operating it print values that simply doesn't make sense, some of them are enormous negative numbers when all the factors are positive.
Please answer me, beacause i dont understand how it can make mistakes in the what is supposed to be the most simple part of the code.
Please post your code. You could be overflowing the maximum values that different types of variables can hold.
Use code tags when you post your program (the '#' button above the row of smileys).
You're probably using signed variables, which when the number gets big enough to make the left most bit a 1, actually goes -ve becasue the left most bit is the sign.
Use unsigned and you'll be good....
edit:
Compare these two, for example:
Show your code.
However, in this case I can psychically determine the issue: Your multiplication results are too big to fit into the type chosen, which might be intermediate types chosen by the compiler to perform constant pre-calculating.
JimboZA:
You're probably using signed variables, which when the number gets big enough to make the left most bit a 1, actually goes -ve becasue the left most bit is the sign.Use unsigned and you'll be good....
Unsigned can overflow, too.
okey, thank you all, ill try what you say.
but, are the negative results also a consequence of the variable limit?
Probably.... since the answer is bigger than the two numbers, it may be that the left bit gets set as 1 so it shows as -ve.
But as Keith says,you need to make sure the unsigned variable is big enough too.
Have a look at all the variable types... int, long, signed, unsigned, and choose the right one.
Yes. as was already said:
You're probably using signed variables, which when the number gets big enough to make the left most bit a 1, actually goes -ve becasue the left most bit is the sign.
it works! Thank you much, you were right, i had to change some int variables to unsigned long.
but be aware that unsigned long can also overflow ,
even the (less known) unsigned long long (64 bit) will overflow some times...
And also be aware that using "unsigned long" may only introduce another problem. It will work if the two multiplicands are always positive. But if you have -1000*1000, this will, of course, overflow a 16-bit integer but it can't be represented in an "unsigned long" either. If you can have negative numbers, you must use "long", not "unsigned long".
Pete
ok, thank, ill take it in account when i need it