Does anyone know of a way to round integers?
I have a button to calculate a random integer out of 60 and then i divide it by 2 and I need it to be a whole number.
I read this and I see:
a) Select a random integer in 1..60.
b) Divide that random integer by 2 NOTE: result must be an integer.
There are 2 simple ways to implement this. In both cases, the simplest thing is to use int's as the datatype, since only int's are used in your requirements.
However, there is a missing requirement: what do you want to do with odd "random integers". Use 31 as an example odd random integer. There are 2 integer values that resemble 31/2 - 15 or 16 - since 31/2 = 15.5. Which do you want?
Option 1 is to simply use int types for everything. Divide by 2 returns an integer.
That's simple code:
Code:
int num;
num = pickRandomInteger(60); // Imagine this function does the random selection
num /= 2; // Done. Eg: 30 -> 15, 31 -> 15
Option 2:
Ok. But now let's say you want to ROUND that number up.
Example: Number picked is 31. Divide by 2 is 16 (not 15.5).
This code is simple, but a brief explanation follows:
Code:
int num;
num = pickRandomInteger(60); // Imagine this function does the random selection
num = (num+1)/2; // Done. Eg: 30 -> 15, 31 -> 16
Here's what happens. Remember that C integer division truncates instead of rounds. Because of that, any non-integer remainers are simply dropped. The "add 1" is similar to the 0.5 in my prior response, as what it does is make integer truncation look like rounding.