开发者

How to find multiple in C#

how might I find out, in an if statement, weather the specified int is a multiple of 5? This is what I mean:

if(X [is a multiple of] 5)
{
    Conso开发者_JAVA技巧le.Writeline("Yes");
}

What would be [is a multiple of]?

Also, why is it that when I do:

if(X = 5)
{
    Console.Writeline("sdjfdslf");
}

it shows "X = 5" in red and tells me "Can not implicitly convert type "int" to "bool"? I am using X as an input.


how might I find out, in an if statement, weather the specified int is a multiple of 5?

You want to use the modulo operation (%).

if (X % 5 == 0) {
    Console.Writeline("Yes");
}

it shows "X = 5" in red and tells me "Can not implicitly convert type "int" to "bool"? I am using X as an input.

The single equals = is assignment. You want the double equals == to do a check for equality.


if (x % 5 == 0) Console.WriteLine("yes");

C# mod operator

Also use == to return a boolean value for a comparison.


You can use the modulus operator (%), which returns the remainder after division:

if (X % 5 == 0) { Console.Writeline("Yes"); }


You're looking for the modulo operator (%) to determine if an integer is a multiple of another integer, like so:

if (x % 5 == 0)

To answer the second part of your question (if (x = 5)), a single equals sign is an assignment operator in C#. You should be using the double equals sign instead, which is the comparison operator, like so: if (x == 5).


= is the assignment operator, while == is used for comparison.

So when your write if (X = 5), you're assigning 5 to X and treat that as a boolean expression.

Interestingly, assigning a value to a variable also returns the value itself.

y = x = 5

assigns 5 to x and assigns the result of (x = 5), which is also 5, to y.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜