If statements and && or ||

后端 未结 12 1323
臣服心动
臣服心动 2020-12-22 02:54

OK so I\'m a beginner with C# and I am having trouble understanding the if statement below.

For this example INumber is declared as 8, dPrice is 0 and dTAX is 10.

12条回答
  •  爱一瞬间的悲伤
    2020-12-22 03:41

    The if condition in this code will always evaluate as true:

    if (iNumber != 8 || iNumber != 9)
    

    When iNumber is 8, it's not equal to 9, so the 2nd part is true. When iNumber is 9, it's not equal to 8, so the first part is true. Anything else, and both sides are true. || conditions result in true with either side is true. There's no way for this to ever be false. You want && here instead of ||:

    if (iNumber != 8 && iNumber != 9)
    

    Or you could use DeMorgan's Law and get this:

    if (! (iNumber == 8 || iNumber == 9))
    

提交回复
热议问题