Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide by 3 and Round up (If need be) C#

Tags:

c#

divide

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?

like image 574
Subby Avatar asked Aug 05 '12 05:08

Subby


3 Answers

Math.Round(num / 3);

or

Math.Ceiling(num / 3);

or

Math.Truncate(num / 3);
like image 98
Inisheer Avatar answered Sep 30 '22 16:09

Inisheer


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.

like image 43
paxdiablo Avatar answered Sep 30 '22 16:09

paxdiablo


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.

like image 36
Jacob Parry Avatar answered Sep 30 '22 16:09

Jacob Parry