codeScrub
codeScrub

Reputation: 53

Operator '&&' can't be applied to operands of type 'int' and 'bool'

im trying to find out if a number that is entered is both divisible by 9 and 13, but it wont let me use the operator i need, i know the variable types are wrong but i dont know how to make it so that the variable types are accepted, im new to coding so can the answer be as basic as possible without taking the piss

public bool IsFizzBuzz(int input)
{
    if ((input % 9) && (input % 13) == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

Upvotes: 5

Views: 22291

Answers (3)

Soner Gönül
Soner Gönül

Reputation: 98750

Since == operator has higher precedence than && operator, your if statements calculates first;

(input % 13) == 0

part and that returns true or false depends on your input. And your if statement will be like;

(input % 9) && true // or false

since input % 9 expression returns int, at the end, your if statement will be;

int && true

and logical AND is meaningless between int and bool variables.

From && Operator (C# Reference)

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

You said;

im trying to find out if a number that is entered is both divisible by 9 and 13

Then you should use them like;

if ((input % 9 == 0) && (input % 13 == 0))

Upvotes: 16

Thomas Levesque
Thomas Levesque

Reputation: 292425

That's because the && operator has a higher priority than the == operator, so the statement is evaluated like this:

if (((input % 9) && (input % 13)) == 0)

Not like this:

if ((input % 9) && ((input % 13) == 0))

Upvotes: 3

marsh
marsh

Reputation: 2720

You cant compare two bracketed statements against one comparison you have to do something like the following.

if( (input % 9 == 0) && (input % 13 == 0) )

Upvotes: 4

Related Questions