What is the difference between System.Math.DivRem()
and the %
operator?
In C#, the modulus operator (%) is an operator that is meant to find the remainder after dividing the first operand (the first number) by the second.
The Modulus Operator (%) For that, C# provides a special operator, modulus ( % ), to retrieve the remainder. For example, the statement 17%4 returns 1 (the remainder after integer division).
The Math. DivRem() method in C# is used to divide and calculate the quotient of two numbers and also returns the remainder in an output parameter.
The symbol used to represent division is the forward slash (/). If you want to divide one number by another, you'll need to place the forward slash character between them. Using the same values for a and b as in the example above, check out how to divide two numbers in C# below: Console.
%
gives you the remainder of a division and discards the quotient altogether, while DivRem()
calculates and returns both the quotient and the remainder.
If you're only concerned about the remainder of a division between two integers, use %
:
int remainder = 10 % 3; Console.WriteLine(remainder); // 1
If you need to know how many times 10 was divided by 3 before having a remainder of 1, use DivRem()
, which returns the quotient and stores the remainder in an out parameter:
int quotient, remainder; quotient = Math.DivRem(10, 3, out remainder); Console.WriteLine(quotient); // 3 Console.WriteLine(remainder); // 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With