Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have next code

int a,b,c;
b=1;
c=36;
a=b%c;

What does "%" operator mean?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
194 views
Welcome To Ask or Share your Answers For Others

1 Answer

It is the modulo (or modulus) operator:

The modulus operator (%) computes the remainder after dividing its first operand by its second.

For example:

class Program
{
    static void Main()
    {
        Console.WriteLine(5 % 2);       // int
        Console.WriteLine(-5 % 2);      // int
        Console.WriteLine(5.0 % 2.2);   // double
        Console.WriteLine(5.0m % 2.2m); // decimal
        Console.WriteLine(-5.2 % 2.0);  // double
    }
}

Sample output:

1
-1
0.6
0.6
-1.2

Note that the result of the % operator is equal to x – (x / y) * y and that if y is zero, a DivideByZeroException is thrown.

If x and y are non-integer values x % y is computed as x – n * y, where n is the largest possible integer that is less than or equal to x / y (more details in the C# 4.0 Specification in section 7.8.3 Remainder operator).

For further details and examples you might want to have a look at the corresponding Wikipedia article:

Modulo operation (on Wikipedia)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...