I am having a temporary lapse of judgement, or not understanding how the power method works, but when I put 10 to the power of a number, it is that value -1. So:
10*10 = 100
Then I would assume, 10^2 = 100
So if I had a variable i
, that was equal to 2
, and I asked arduino for 10
to the power of i
, I would expect it to do 10^2
, and then give me 100
, but instead I get 99
. What am I missing?
void setup() {
Serial.begin(9600);
}
void loop() {
for (int i =0; i<5; i++){
int power = i;
Serial.print(power);
Serial.print(":");
int multiplier = pow(10,power);
Serial.println(multiplier);
}
}
-
^ is not power operator in C and C++. it is bitwise XORJuraj– Juraj ♦2018年11月06日 05:30:20 +00:00Commented Nov 6, 2018 at 5:30
-
stackoverflow.com/questions/4843304/…Juraj– Juraj ♦2018年11月06日 05:32:37 +00:00Commented Nov 6, 2018 at 5:32
2 Answers 2
pow()
works with floating point numbers.
Floating point numbers are just an approximation. You will very rarely get precise results using floating point numbers.
Instead you could write your own little integer-based ipow()
function.
I put this code into the IDE, and for n>=2, I got 99, 999, 9999 etc. The catch is that Arduino uses floating point arithmetic to implement the pow() function, and some of your values are being truncated as ints. If you change:
int multiplier = pow(10,power);
to
float multiplier = pow(10,power);
The results should be as expected.
(The brief reason why floats are used is related to the fact that it is very easy to calculate the pow() function using logs, and this makes it easy to pow() non-integers too. This also means that it may not be as exact as you would hope).