Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "Math.DivRem" and % operator?

Tags:

What is the difference between System.Math.DivRem() and the % operator?

like image 293
mbrownnyc Avatar asked Aug 08 '11 20:08

mbrownnyc


People also ask

What is the MOD operator in C#?

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.

How do you find the remainder in C sharp?

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).

How does C# calculate reminders?

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.

How do you divide in C sharp?

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.


1 Answers

% 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 
like image 171
BoltClock Avatar answered Sep 21 '22 18:09

BoltClock