Arduino - Writing int array with for loop doesn't work
I am a college student so I am still learning a lot. During the creation of the project, I came across something interesting. I have this segment of code that works when it doesn't fit in a for loop, but doesn't work when it is. I just want to understand why. Here is my code:
void setup() {
Serial.begin(9600);
int a[8];
for(int i=0;i<8;i++) {
a[i]=pow(2,i);
}
for(int i=0;i<8;i++) {
Serial.print(a[i]);
}
}
void loop() {
}
Here's the same code, written without the first for loop (where data is written to an array):
void setup() {
Serial.begin(9600);
int a[8];
a[0]=pow(2,0);
a[1]=pow(2,1);
a[2]=pow(2,2);
a[3]=pow(2,3);
a[4]=pow(2,4);
a[5]=pow(2,5);
a[6]=pow(2,6);
a[7]=pow(2,7);
for(int i=0;i<8;i++) {
Serial.print(a[i]);
}
}
void loop() {
}
First code outputs:
1 2 3 7 15 31 63 127
While the second code outputs:
1 2 4 8 16 32 64 128
Somebody knows? I really want to know why.
source to share
You have a floating point ending. 2 ^ 4 will actually give you a value closer to 15.9999, and when an int is assigned to it, it truncates the decimal to 15. I would suggest doing bit changing operations when using powers of 2, for example:
for(int i=0;i<8;i++)
{
a[i]=(1 << i);
}
If you want to read bit switching take a look here . If you want to know more about floating point rounding take a look here .
Also, if you'd like to just adjust your code closer to what you have, I believe this will work as well:
for(int i=0;i<8;i++)
{
a[i]= (int) round( pow(2, i) );
}
This will round the floating result correctly before passing it to an int.
source to share