Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The opposite of the modulo operator?

I remember in java that, the modulo operator could be inverted so that rather than seeing what the remainder is of an operation, you could invert it, so instead it will tell you many times a number was divided by:

Console.WriteLine(1000 % 90);
Console.WriteLine(100 % 90);
Console.WriteLine(81 % 80);
Console.WriteLine(1 % 1);

Output:

  • 10
  • 10
  • 1
  • 0

Examples courtesy of DotNetPerls

Rather than seeing the remainder, I want to see how many times '80' went into '81'. Which should be 1 with a remainder of 1.

Does the c# modulo operator support this behaviour? If not, how might achieve the desired behaviour? With minimal code please ... :D

EDIT:

I imagine the answer is going to be something simple like dividing the two numbers and getting rid of the '-.#' value and keeping the integer '1.-'. I know about this but there must be a slicker way of doing this?

like image 870
IbrarMumtaz Avatar asked Jul 14 '12 22:07

IbrarMumtaz


2 Answers

What you are looking for is called integer division. It is not related to the modulo operator at all.

To perform an integer division, simply ensure that neither operand is a float/double.

Example:

int one = 81 / 80;

This gives you 1 while double notOne = 81.0 / 80 would give you 1.0125 for example.

like image 127
ThiefMaster Avatar answered Sep 21 '22 19:09

ThiefMaster


You already got the answer, no need to deal with the decimals if you assign it to an integer.

In your comment you say that you are working with decimals, then Math.Floor is a possibility. ie:

double d = Math.Floor(81.0 / 80.0); // 1.0000....
like image 43
Avada Kedavra Avatar answered Sep 21 '22 19:09

Avada Kedavra