Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 881
codeScrub Avatar asked Nov 26 '14 18:11

codeScrub


People also ask

What is operator and example?

In mathematics and computer programming, an operator is a character that represents a specific mathematical or logical action or process. For instance, "x" is an arithmetic operator that indicates multiplication, while "&&" is a logical operator representing the logical AND function in programming.

What are the seven 7 types of operator?

In Python, there are seven different types of operators: arithmetic operators, assignment operators, comparison operators, logical operators, identity operators, membership operators, and boolean operators.

What is operator and function?

An operator function is a user-defined function, such as plus() or equal(), that has a corresponding operator symbol. For an operator function to operate on the opaque data type, you must overload the routine for the opaque data type.


3 Answers

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))
like image 161
Soner Gönül Avatar answered Oct 27 '22 03:10

Soner Gönül


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

if( (input % 9 == 0) && (input % 13 == 0) )
like image 4
marsh Avatar answered Oct 27 '22 03:10

marsh


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))
like image 3
Thomas Levesque Avatar answered Oct 27 '22 03:10

Thomas Levesque