If statements and && or ||

后端 未结 12 1275
臣服心动
臣服心动 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:31

    The following is from MSDN:

    The conditional-OR operator (||) performs a logical-OR of its bool operands. If the first operand evaluates to true, the second operand isn't evaluated. If the first operand evaluates to false, the second operator determines whether the OR expression as a whole evaluates to true or false.

    In your example the first condition (!=8) is false because iNumber = 8, but the second condition is (!=9), which is true. So that's why it goes into the braces.

    If instead you say !=8 && !=9, it will not go in the braces because it doesn't satisfy both conditions.

    0 讨论(0)
  • 2020-12-22 03:32

    The statement is logically equivalent to

        if (!(iNumber == 8 && iNumber == 9))
        {
            dPrice = dPrice + dTAX;
        }
    

    which is ALWAYS true since a number cannot be both 8 and 9.

    You want:

        if (iNumber != 8 && iNumber != 9)
        {
            dPrice = dPrice + dTAX;
        }
    

    or

        if (!(iNumber == 8 || iNumber == 9))
        {
            dPrice = dPrice + dTAX;
        }
    

    whichever makes more sense to you, logically.

    0 讨论(0)
  • 2020-12-22 03:40

    In English, this reads as: If iNumber is not 8 OR iNumber is not 9. iNumber is 8, which IS NOT 9 (your second check), so it drops into the if block.

    You're describing an AND condition where it doesn't equal 8 and it doesn't equal 9.

    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 2020-12-22 03:43

    It is entering the statement because the statement becomes true when it calculates iNumber != 9

    An || (Or Operator) in an if will be true if any statement is true.

    Think of it this way..

    8 != 8 is False
    8 != 9 is True
    
    if ( False || True )
    {
        //Do Stuff
    }
    
    0 讨论(0)
  • 2020-12-22 03:43

    The || OR operator means only one OR the other has to be true. In this case, iNumber != 9, so that portion of the code is true and it enters the statement. I think you'll want to use the && AND operator to indicate that it can't be 8 AND it can't be 9.

    0 讨论(0)
提交回复
热议问题