- Home /
Divisible by 3
I need to take an int variable that that will never be the same number, and check to see if it is divisible by 3. If it is not, I need to find the nearest number that is. Any suggestions?
if you know that it needs to be divisible by 3 you can set a array to hold all the possibilities then run a random selection from the array
Are you generating the random numbers yourself, or just checking if it's divisible by 3? You know about the % operator, right?
you can use a loop that changes a variable and check it every interaction but... my instinct says whatever you are trying to archive there is a better way than dividing by 3 and find closest number. Why don't you explain what you are trying to do?
Answer by KMKxJOEY1 · Jan 12, 2015 at 01:17 AM
if(integer % 3 != 0) //this is if the integer is not divisible by 3
{
integer += integer % 3; //this will add the remained of /3, therefor finding the next multiple
}
Nice work on the %. But your implementation is slightly off. If should be
if(integer % 3 != 0) {
integer -= integer % 3;
}
Or if we want to ceil ins$$anonymous$$d of floor
if(integer % 3 != 0) {
integer += 3 - integer % 3;
}
Ideally you would wrap the whole thing in a method call, make the hard coded 3 an operator, and implement rounding.
Answer by Kiwasi · Jan 12, 2015 at 02:14 AM
You could also use
newInt = oldInt / 3 * 3;
This solution will round towards zero.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Pass a function(float) as variable 2 Answers
Displaying variable on UI text every frame (JS) 1 Answer
Script not changing int variable 2 Answers
Subtract from Integer 3 Answers