Problem with pow(); function


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 = ");

with powers of 0 and 1 the results are correct. Power of 3 results in 999 instead of 1000.

Have I overlooked something?


Yes. Google. :wink:

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.

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;