Programming (probably bad programming) question

Post here about your Arduino projects, get help - for Adafruit customers!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
henry.best
 
Posts: 13
Joined: Sat Mar 03, 2012 9:37 pm

Programming (probably bad programming) question

Post by henry.best »

This compiles! :shock:
But how does the Arduino cope with this sort of error.

Code: Select all

void loop() {
  uint8_t i;
  i=255;
  i=i/7;
}
255/7 =36 and 5/7ths. As the result is being stored in an 8 bit int, does it get rounded up/down before storage or what? I may need to do this sort of division, but don't need the fractional part for my programme, only the int, as it will be controlling the speed of a motor which doesn't need to be highly accurate.

User avatar
westfw
 
Posts: 2008
Joined: Fri Apr 27, 2007 1:01 pm

Re: Programming (probably bad programming) question

Post by westfw »

The result is truncated. 255/7 = 36.
It's not considered an error; just standard rules for "integer" division.
Note that it will NOT "round."

If you've got an Arduino, you could just try it out.
Actually, you could try this out anywhere that has a C compiler; it better give the same results!

User avatar
henry.best
 
Posts: 13
Joined: Sat Mar 03, 2012 9:37 pm

Re: Programming (probably bad programming) question

Post by henry.best »

Thanks for that. It's what I though would happen but I wanted it confirmed.

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino”