带示例的帖子增量

时间:2018-07-12 15:03:15

标签: java

我对以下表达式有些困惑。在这里:

char a = 'D';
int b = 5;
System.out.println(a++/b+--a*b++);

我正在尝试通过以下方式解决该问题:

  1. ('D'/b+--a*b++);

幕后a = 'E'

  1. 'D'/b+'D'*b++;

  2. 'D'/b + 'D' * 5;

幕后b的值增加到6,b = 6

  1. 'D'/6 + 'D' *5;

  2. 11 + 'D' * 5;

  3. 11 + 345

由于D的ASCII值为69

  1. 356

但是编译器给出的输出为353。我在这里做的错误是什么?

2 个答案:

答案 0 :(得分:4)

您正在计算的是

(a++ / b) + (--a * b++)

在此expression中,--a取消了a++之后除数a的值为E,但< em>之前,它再次具有值D。后增量和前减量相互抵消。因此,/*的第一个操作数是'D',即68。后递增b++对表达式没有影响。你呢

(68 / 5) + (68 * 5)

353使用整数舍入。

编辑:详细情况是这样的:

char a = 'D';
int b = 5;

int divisonResult = a / b;

// a++ and --a cancel each other.
a++; // The incrementation of a happens after the divison.
--a; // The decrementation of a happens before the multiplication.

// Now a is back to 'D'.
int multiplicationResult = a * b;

b++; // This has no effect since b takes no part in the last step:

int additionResult = divisonResult + multiplicationResult;

答案 1 :(得分:0)

正如Lurz Horn所指出的那样,我在旧答案中犯了一个错误,我的测试通过了,因为错误小于1,并且被整数切除。因此,我迅速编辑了测试,现在正在处理双打。

老实说,我也很感兴趣,所以我以单元测试的形式逐步将其分开。最后的测试最好地显示了编译器是如何执行的。

  @Test
  public void test1() throws Exception {
    char a = 'D';
    double b = 5;

    double result = a++ / b + --a * b++;

    assertThat(result, is(closeTo(353.6, 0.001)));
  }

  @Test
  public void test2() throws Exception {
    char a = 'D';
    double b = 5;

    double aDividedB = a++ / b;
    double result = aDividedB + --a * b++;

    assertThat(result, is(closeTo(353.6, 0.001)));
  }

  @Test
  public void test3() throws Exception {
    char a = 'D';
    double b = 5;

    double aDividedB = a / b;
    a++;
    double result = aDividedB + --a * b++;

    assertThat(result, is(closeTo(353.6, 0.001)));
  }

  @Test
  public void test4() throws Exception {
    char a = 'D';
    double b = 5;

    double aDividedB = a / b;
    a++;
    double aTimesB = --a * b++;
    double result = aDividedB + aTimesB;

    assertThat(result, is(closeTo(353.6, 0.001)));
  }

  @Test
  public void test5() throws Exception {
    char a = 'D';
    double b = 5;

    double aDividedB = a / b;
    a++;
    a--;
    double aTimesB = a * b++;
    double result = aDividedB + aTimesB;

    assertThat(result, is(closeTo(353.6, 0.001)));
  }

  @Test
  public void test6() throws Exception {
    char a = 'D';
    double b = 5;

    double aDividedB = a / b;
    a++;
    a--;
    double aTimesB = a * b;
    b++;
    double result = aDividedB + aTimesB;

    assertThat(result, is(closeTo(353.6, 0.001)));
  }