user513064
user513064

Reputation:

Specifically, what does % do in C#?

I have never came across anything that requires me to use it, and when I google what it does nothing comes up.

So, can someone please explain in detail, what does it do?

Upvotes: 2

Views: 1143

Answers (4)

Keith Lashley
Keith Lashley

Reputation: 37

It lets you know what is left over once the first number has been divided by the second as many times as it can. For example:

  • 5 % 2 = 1

    • Because 2 can only go into 5, 2 times (4), then all you have is 1 left over.
  • 5 % 2.2 = 0.6

    • Because 2.2*2 is 4.4 and 5-4.4 is 0.6.

Upvotes: -1

gideon
gideon

Reputation: 19465

Its the modulus operator.

See the MSDN Link, although it doesn't have a great example.

It basically gets the remainder, when the first number is divided by the second.

Like 7 % 3 = 1. You can play with this on google.

As MSDN Example says, modding different types (doubles,decimals) results those types.

The most common use is in programs that need to check for an even number:

 n % 2 == 0;// if the mod of n by 2 (remainder) is zero then n is even

Specifically like @BenVoigt says modulus actually takes the sign of the dividend.(unlike remainder which takes the sign of the divisor) It seems some languages implement it this way, there is a list here on wikipedia. So C# takes the sign of the dividend.

-7 % 3 = -1//in C#
-6 % 2 = 0// so even checks work ok with negative numbers in C#

But the result from google is 2?

Upvotes: 4

Ed Chapel
Ed Chapel

Reputation: 6932

It is the modulus operator

http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx

Upvotes: 0

mdm
mdm

Reputation: 12630

It is the Modulo Operation. Returns the remainder when one integer is divided by another.

Upvotes: 4

Related Questions