5

I have come to a point in my game where I have to implement a feature which divides a number by 3 and makes it a whole integer. i.e. not 3.5 or 2.6 etc....

It was to be a whole number, like 3, or 5.

Does anyone know how I can do this?

Subby
  • 5,370
  • 15
  • 70
  • 125

3 Answers3

11
Math.Round(num / 3);

or

Math.Ceiling(num / 3);

or

Math.Truncate(num / 3);
Inisheer
  • 20,376
  • 9
  • 50
  • 82
  • 1
    This worked for me: gameManager.maxTries = (int)Math.Ceiling((double)gameManager.GameLevelImages[gameManager.GameLevel] / 3); Thank you – Subby Aug 05 '12 at 05:37
  • 2
    It's really important to know if `num` is an integer or not. If `num` is a floating-point type (or `decimal`), the above answer makes sense. If on the other hand `num` is an integer type, like `int`, the division will already truncate to return an integer result. To avoid that, write the denomiantor as `3.0` instead of just `3`. **Or** cast either the numerator or the denominator to `double` (like in the comment above). – Jeppe Stig Nielsen Aug 05 '12 at 05:50
  • @JeppeStigNielsen True, my assumption was that he/she was working with floating point numbers. – Inisheer Aug 05 '12 at 05:51
7

Divide by three and round up can be done with the math functions:

int xyzzy = Math.Ceiling (plugh / 3);

or, if the input is an integer, with no functions at all:

int xyzzy = (plugh + 2) / 3;

This can also be done in a more generic way, "divide by n, rounding up":

int xyzzy = (plugh + n - 1) / n;

The Ceiling function is for explicitly rounding up (towards positive infinity). There are many other variations of rounding (floor, truncate, round to even, round away from zero and so on), which can be found in this answer.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • More generically, int xyzzy = (plugh + n - 1) / n; The + n forces the round up, and the - 1 avoids it rounding up when it would have divided perfectly. – thelem Dec 16 '14 at 11:45
4

Found this which says that if you take the number to divide, add two, and divide by three you would get the correct answer. For example, 7/3 = 2.3, but (7+2)/3 = 3.

Community
  • 1
  • 1
Jacob Parry
  • 120
  • 8