【问题标题】:Increment/Decrement Confusion递增/递减混淆
【发布时间】:2021-02-03 08:15:25
【问题描述】:

当我们在这里减少代码时会发生什么:

temp[--countArray[getDigit(position, input[tempIndex], radix)]]

如果在这种情况下 temp 为 1:我们是否首先递减以便分配为 0?这种减少有多迅速?它似乎总是让我在数组括号中感到困惑。

【问题讨论】:

  • 它递减countArray[getDigit(position, input[tempIndex], radix)]并将递减的值用作temp的索引。
  • "如果在这种情况下 countArray 为 1"—countArray 不能为 1。它必须是一个数组。
  • @khelwood 我的错误,意思是写'if temp index is 1'

标签: java increment decrement


【解决方案1】:

让我分解一下。下面是一些与上面等价的代码:

int digit = getDigit(position, input[tempIndex], radix);
countArray[digit]--;
int count = countArray[digit];
temp[count] // Do something with the value

顺便说一句,这是一个经典的例子,说明了为什么你不应该为了简洁而牺牲清晰度。

【讨论】:

    【解决方案2】:

    尝试在不同的缩进级别解开括号:

    temp[                                                // get this index in temp
        --                                               // decrement by 1
        countArray[                                      // get this index in countArray
            getDigit(position, input[tempIndex], radix)  // call getDigit()
        ]
    ]
    

    在人类可读的术语中,它调用getDigit() 来索引countArray,然后递减该值并使用它来索引temp


    递减运算符--xx-- 不同,因为它返回的是什么。到操作结束时,x 总是以比原来小一结束,但 --x 返回 xnew 值,而 x-- 返回 old x 的值从递减前开始。这同样适用于++xx++

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-27
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      • 2014-06-17
      相关资源
      最近更新 更多