BlueEagles
BlueEagles

Reputation: 41

Arduino - Writing int array with for loop doesn't work

I am a college student so I'm still learning a lot. I ran into something interesting while making a project. I have this segment of code that works when it isn't placed 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 is the same code written without the first for loop (where the data gets written into the 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() {
}

The first code outputs:

1
2
3
7
15
31
63
127

While the second code outputs:

1
2
4
8
16
32
64
128

Does anybody know? I really want to know why.

Upvotes: 3

Views: 436

Answers (1)

Easton Bornemeier
Easton Bornemeier

Reputation: 1936

You are experiencing floating point round off. 2^4 will actually give you a value closer to 15.9999 and when this is assigned to an int, it truncates the decimal to 15. I would suggest doing bit shift operations when using powers of 2, such that:

  for(int i=0;i<8;i++)
  {
    a[i]=(1 << i);
  }

If you want to read up on bit shifting, look here. If you want to know more about the floating point round off, look here.

Additionally if you wanted just a quick fix to your code closer to what you have, I believe this will also work:

  for(int i=0;i<8;i++)
  {
    a[i]= (int) round( pow(2, i) );
  }

This will round the floating result properly before casting it to an int.

Upvotes: 6

Related Questions