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

无人久伴 提交于 2019-12-23 13:16:08

问题


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

回答1:


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



回答2:


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

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



回答3:


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


来源:https://stackoverflow.com/questions/27156668/operator-cant-be-applied-to-operands-of-type-int-and-bool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!