naut
February 28, 2014, 8:04pm
1
hi
I'm getting false results from the pow(); function, e.g. the following code prints 99 instead of 100.
byte p = 2;
unsigned int power10 = pow(10, p);
Serial.print("power10 = ");
Serial.println(power10);
with powers of 0 and 1 the results are correct. Power of 3 results in 999 instead of 1000.
Have I overlooked something?
thanks
The result of the pow() function is a floating point number and that will very rarely be exactly equal to an integer value. In the "incorrect" case you are probably converting a result like 999.999 to 999 by the integer truncation.
naut
February 28, 2014, 11:54pm
4
thanks guys,
ye, I should've searched b4 creating the topic.
In any case I replaced the pow() function with a switch function and a few cases.
another option is create a function for integer power like
long ipow(int a, uint8_t b)
{
long rv = 1;
for (uint8_t i = 0; i < b; ++i) rv *= a;
return rv;
}