search

Home  >  Q&A  >  body text

javascript - The value of the ternary arithmetic expression 3<8?(9<6?7:5):2>0?4:1 is different in Java and PHP. What is the solution?


The evaluation result in java and js is 5, but in PHP it is 4
Is it because my formula is not written in a standard way? Or is it for other reasons? I asked others to try it using .net and c language, and all the results were 5
[Solved] Thank you for your answers. My guess is that the formula is not very standardized, because I always feel that The ternary is from right to left, so I omitted the last bracket (I often wrote it this way before). I will correct it. For the sake of standardization, it should be 3<8?(9<6?7:5):(2>0 ?4:1)

三叔三叔2718 days ago1032

reply all(6)I'll reply

  • typecho

    typecho2017-06-08 11:04:07

    The problem with the combination direction of the ternary operator:
    java from right to left. Equivalent to 3<8?(9<6?7:5):(2>0?4:1)
    php from do to right. Equivalent to (3<8?(9<6?7:5):2)>0?4:1

    Therefore, in order to avoid the generation of ambiguous code, it is better not to omit the parentheses that should be written

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-08 11:04:07

    PHP’s ternary operation combination order is reverse
    http://www.jianshu.com/p/124f...

    reply
    0
  • 代言

    代言2017-06-08 11:04:07

    I guess PHP interprets priorities differently from Java, JS and other languages. It may be interpreted as (3 < 8 ? (9 < 6 ? 7 : 5) : 2 > 0) ? 4 : 1

    reply
    0
  • 某草草

    某草草2017-06-08 11:04:07

    In PHP it looks like this:

    $a = (3 < 8 ? (9 < 6 ? 7 : 5): 2 > 0)
        ? 4
        : 1;

    So it’s 4;

    In JavaScript it looks like this:

    var a = (3 < 8)
        ? (9 < 6 ? 7 : 5)
        : (2 > 0 ? 4 : 1);

    So it’s 5.

    So if you don’t know the precedence of the operator, just complete the brackets. ^_^

    reply
    0
  • 怪我咯

    怪我咯2017-06-08 11:04:07

    Correct answer upstairs~~~~~~

    reply
    0
  • 欧阳克

    欧阳克2017-06-08 11:04:07

    Shouldn’t I type this photo?

    reply
    0
  • Cancelreply