Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/358.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中代码的执行顺序_Java_Int_Operators_Double - Fatal编程技术网

java中代码的执行顺序

java中代码的执行顺序,java,int,operators,double,Java,Int,Operators,Double,我正在运行以下代码 int x=4; int y=3; double z=1.5; z=++x/y*(x-- +2); int t=(++x/y); System.out.println(z); //7 想知道它是如何在什么时候产生7的吗 (x--+2)=6 ++x/y=1.6666 3=6*1.6666=10 评估结果如下: z = ++x / y * (x-- + 2); // Substitute value of ++x, y and x-- = 5 / 3 * (5 +

我正在运行以下代码

int x=4;
int y=3;
double z=1.5;
z=++x/y*(x-- +2);
int t=(++x/y);
    System.out.println(z); //7
想知道它是如何在什么时候产生7的吗

  • (x--+2)=6
  • ++x/y=1.6666

    3=6*1.6666=10

  • 评估结果如下:

    z = ++x / y * (x-- + 2);  // Substitute value of ++x, y and x--
      = 5 / 3 * (5 + 2);      // After this point, x will be 4. Evaluate parenthesized expr
      = 5 / 3 * 7   // Now, left-to-right evaluation follows
      = 1 * 7       // 5 / 3 due to integer division will give you 1, and not 1.66
    
    z=((++x)/y)*(x-- +2);
    
    以及:


    代码评估为:

    z = ++x / y * (x-- + 2);  // Substitute value of ++x, y and x--
      = 5 / 3 * (5 + 2);      // After this point, x will be 4. Evaluate parenthesized expr
      = 5 / 3 * 7   // Now, left-to-right evaluation follows
      = 1 * 7       // 5 / 3 due to integer division will give you 1, and not 1.66
    
    z=((++x)/y)*(x-- +2);
    
    x和y都是int,因此每个步骤的计算结果将转换为int类型。这意味着
    5/3=1

    最后,结果被分配给一个双变量,因此
    7
    将被转换为
    7.0

    将代码修改为:

    z=1.0 * ((++x)/y)*(x-- +2);
    

    您将得到一个十进制结果。

    (++x/y)这是如何首先执行的,因为它不在圆括号中。。()应该被评估first@user1765876尽管将首先对零件进行求值,但这不会对结果产生任何影响。由于计算前将替换
    ++x
    x的值--
    。@user1765876删除了括号。现在应该很清楚了。++或--before(leftside)时,它被递增或递减,然后立即表达式被求值。++或者--当在变量后面(右侧)时,首先计算立即表达式,然后将新值分配给变量。@user1765876括号中的表达式将首先计算。但在评估之前,将替换所有变量的值。因此,对于
    y/x++*(x--+1)
    x--
    的值将在
    x++
    的值之后求值。然后,
    (x--+1)
    将作为
    y/x++
    之前的表达式进行计算。