TL ; DR:
The
Math.Floor()method returns the largest integer less than or equal to a given number:Console.WriteLine(Math.Floor(3.9)); // Output: 3 Console.WriteLine(Math.Floor(5.2)); // Output: 5 Console.WriteLine(Math.Floor(7.0)); // Output: 7We can use this method if we want to compute the integral part of some division (quotient). It needs a
double, so we divide with20.0or cast one operand:int a = 3; int b = 7; Console.WriteLine(Math.Floor(20.0 / a)); // Output: 6 Console.WriteLine(Math.Floor((double)b / a)); // Output: 2When both operands are
int, C# divides without a fractional part, so20 / ais already6.
Full lesson:
Remember how we first learn about the division of two integer numbers in primary school?
The quotient is the number of times a division is completed fully, while the remainder is the amount left that doesn't entirely go into the divisor.
Here are some examples:
10 / 2 = quotient 5, remainder 0
15 / 4 = quotient 3, remainder 3
20 / 3 = quotient 6, remainder 2
Floor division
When we divide two int values with /, C# returns only the integral part of the result (the quotient), so there is no separate floor division operator:
Console.WriteLine(10 / 2); // Output: 5
Console.WriteLine(15 / 4); // Output: 3
Console.WriteLine(20 / 3); // Output: 6
It can also be used with variables:
int a = 3;
int b = 7;
Console.WriteLine(20 / a); // Output: 6
Console.WriteLine(b / a); // Output: 2
Modulo
The modulo operator (%) calculates the remainder of dividing two values:
Console.WriteLine(10 % 2); // Output: 0
Console.WriteLine(15 % 4); // Output: 3
Console.WriteLine(20 % 3); // Output: 2
// Can be used with variables:
int a = 2;
int b = 4;
Console.WriteLine(b % a); // Output: 0
Console.WriteLine(11 % b); // Output: 3
Quotient and remainder
In programming, we combine both these concepts to get the quotient and remainder of some divison:
// Let's divide 26 by 3:
int quotient = 26 / 3;
int remainder = 26 % 3;
Console.WriteLine(quotient); // Output: 8
Console.WriteLine(remainder); // Output: 2
Assignment
Follow the Coding Tutorial and let's practice with quotient and remainder!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
