Check if int is between two numbers

后端 未结 10 956
夕颜
夕颜 2020-11-28 13:09

Why can\'t do you this if you try to find out whether an int is between to numbers:

if(10 < x < 20)

Instead of it, you\'ll have to do

相关标签:
10条回答
  • 2020-11-28 13:40

    One problem is that a ternary relational construct would introduce serious parser problems:

    <expr> ::= <expr> <rel-op> <expr> |
               ... |
               <expr> <rel-op> <expr> <rel-op> <expr>
    

    When you try to express a grammar with those productions using a typical PGS, you'll find that there is a shift-reduce conflict at the point of the first <rel-op>. The parse needs to lookahead an arbitrary number of symbols to see if there is a second <rel-op> before it can decide whether the binary or ternary form has been used. In this case, you could not simply ignore the conflict because that would result in incorrect parses.

    I'm not saying that this grammar is fatally ambiguous. But I think you'd need a backtracking parser to deal with it correctly. And that is a serious problem for a programming language where fast compilation is a major selling point.

    0 讨论(0)
  • 2020-11-28 13:40

    You could make your own

    public static boolean isBetween(int a, int b, int c) {
        return b > a ? c > a && c < b : c > b && c < a;
    }
    

    Edit: sorry checks if c is between a and b

    0 讨论(0)
  • 2020-11-28 13:45

    simplifying:

    a = 10; b = 15; c = 20
    
    public static boolean check(int a, int b, int c) {
        return a<=b && b<=c;
    }
    

    This checks if b is between a and c

    0 讨论(0)
  • 2020-11-28 13:49

    COBOL allows that (I am sure some other languages do as well). Java inherited most of it's syntax from C which doesn't allow it.

    0 讨论(0)
  • 2020-11-28 13:50

    Because that syntax simply isn't defined? Besides, x < y evaluates as a bool, so what does bool < int mean? It isn't really an overhead; besides, you could write a utility method if you really want - isBetween(10,x,20) - I wouldn't myself, but hey...

    0 讨论(0)
  • 2020-11-28 13:51

    if (10 < x || x < 20)

    This statement will evaluate true for numbers between 10 and 20. This is a rough equivalent to 10 < x < 20

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