Check if int is between two numbers

后端 未结 10 957
夕颜
夕颜 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:54

    It's just the syntax. '<' is a binary operation, and most languages don't make it transitive. They could have made it like the way you say, but then somebody would be asking why you can't do other operations in trinary as well. "if (12 < x != 5)"?

    Syntax is always a trade-off between complexity, expressiveness and readability. Different language designers make different choices. For instance, SQL has "x BETWEEN y AND z", where x, y, and z can individually or all be columns, constants, or bound variables. And I'm happy to use it in SQL, and I'm equally happy not to worry about why it's not in Java.

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

    You are human, and therefore you understand what the term "10 < x < 20" suppose to mean. The computer doesn't have this intuition, so it reads it as: "(10 < x) < 20".

    For example, if x = 15, it will calculate:

    (10 < x) => TRUE

    "TRUE < 20" => ???

    In C programming, it will be worse, since there are no True\False values. If x = 5, the calculation will be:

    10 < x => 0 (the value of False)

    0 < 20 => non-0 number (True)

    and therefore "10 < 5 < 20" will return True! :S

    0 讨论(0)
  • 2020-11-28 14:01

    The inconvenience of typing 10 < x && x < 20 is minimal compared to the increase in language complexity if one would allow 10 < x < 20, so the designers of the Java language decided against supporting it.

    0 讨论(0)
  • 2020-11-28 14:07

    Because the < operator (and most others) are binary operators (they take two arguments), and (true true) is not a valid boolean expression.

    The Java language designers could have designed the language to allow syntax like the type you prefer, but (I'm guessing) they decided that it was not worth the more complex parsing rules.

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