Search code examples
c#intbooleanoperators

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;
    }
}

Solution

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