|
|
View previous topic :: View next topic |
Author |
Message |
Richard Guest
|
dividing |
Posted: Mon May 24, 2004 5:35 am |
|
|
Dear Friends
I want to code an alogorithm to detect multiples of say 8 from a variable
i.e
8/8 =1 it has occured once
9/8=1.125
10/8=1.25
etc.......
etc.....
16/8 = it has occured twice
Can anyone tell me how I would detect if there was no remainder
i.e an exact multiple of 8.
Can you please give me an example!! |
|
|
.C
Joined: 06 May 2004 Posts: 19 Location: Italy
|
|
Posted: Mon May 24, 2004 6:24 am |
|
|
try this:
#define true 1
int Test;
short int multiple;
Test =64;
if ( ! (Test % 8) ) multiple=true; |
|
|
Ttelmah Guest
|
Re: dividing |
Posted: Mon May 24, 2004 6:26 am |
|
|
Richard wrote: | Dear Friends
I want to code an alogorithm to detect multiples of say 8 from a variable
i.e
8/8 =1 it has occured once
9/8=1.125
10/8=1.25
etc.......
etc.....
16/8 = it has occured twice
Can anyone tell me how I would detect if there was no remainder
i.e an exact multiple of 8.
Can you please give me an example!! |
The modulus function.
if ((val%8) == 0) //do what you want here.
Alternatively (quicker if your test is for '8', rather than any number), use the bitwise and, with:
if ((val & 7) == 0) //operations here.
The '%', returns the remainder from dividing the first number by the second.
The second route, takes advantage of the fact that numbers are stored in binary, so:
8 = 0001000
9 = 0001001
16 = 0010000
17 = 0010001
If you 'AND' these numbers with 7, you get:
8 & 7 = 0
9 & 7 = 1
16 & 7 = 0
17 & 7 = 1
etc.
The result will only be 'zero', when the number is an exact multiple of 8.
Best Wishes |
|
|
Birdie Guest
|
|
Posted: Mon May 24, 2004 7:00 am |
|
|
There is another option that gives all the information regarding the result of the test, both quotient and remainder (if you need it):
ldiv_t test;
signed long test_value;
long times_occurred;
test_value = 64;
test = ldiv(test_value,8);
if(test.rem == 0)
times_occurred = test.quot;
This ldiv function is also good for shrinking code size when using printf() with a float value. As a substitute:
ldiv_t tempory;
float PrintValue;
PrintValue = 347.8;
PrintValue *= 10;
tempory = ldiv((signed long)PrintValue,10);
printf(lcd_putc,"%ld.%1ld",tempory.quot,tempory.rem); |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|