# trouble with function Pow in for loop

Hi! My code is

``````int y=0;
int i=0;

void setup()
{
Serial.begin(9600);
}

void loop()
{
for (int i=0; i<9; i++)
{
y=pow(2,i);
Serial.print(i);
Serial.print("   ");

Serial.println(y);
delay(1000 / 2);
}
}
``````

but it give me:

``````0   1
1   2
2   3
3   7
4   15
5   31
6   63
7   127
8   255
``````

Just “pow(2,2)” give 4, “pow(2,3)” - 8, etc.
I tried to change “int i=0” to “char i=0”; “for()” to “do … while”; “i”, “y” to “i2”, “y2”; “Serial.println(y)” to “Serial.println(y, DEC)”;

Any suggestions?

y=pow(2,i);

…use shift-left…

y = 1 << i;

pow returns a float. When you cast it to int, the fractional part was lost. Try declaring y as a float instead if you want to use pow.

Coding Badly, thx! But i just want replace shift-left to pow(a,b). :)

Thanks!

According to the language reference, the base & exponent values passed-in should also be floats.

With floating-point (binary floating-point inside the computer) you can get some "strange" rounding errors, so 2.0 x 2.0 might equal 3.999999999 (or something like that). So, it's usually a good idea to write a few lines of code to round-off. If you truncate (simply throw-away digits), 3.9 becomes 3.