【问题标题】:I need to decrease first n elements of an array by 1我需要将数组的前 n 个元素减少 1
【发布时间】:2019-11-27 18:25:46
【问题描述】:

我想将数组中的前 n 个元素减 1。我试过了,但它不起作用

int n = 3;

for(int i = 0 ; i <array.length;i++) {

        while(i<=n){

         array[i]-=1;
         }          

}

【问题讨论】:

  • 嗯,为什么不在你的 for 循环中 i &lt; n 并摆脱你的 while 循环。否则你在while循环中的i永远不会增加,因此它会卡住

标签: java arrays


【解决方案1】:

假设n=3

int n =3;

for(i = n-1; i >= 0; i--)
{
    array[i]-=1;
}

另外,正如@locus2k 指出的那样,我们也可以从第 0 个索引开始遍历数组

int n = 3;
for(i = 0; i < n; i++)
{
    array[i]-=1;
}

【讨论】:

  • 为什么不for(i = 0; i &lt; n; i++)
  • 没错,我只是想更多地考虑OP想要第一个n所以0-n
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-06
  • 1970-01-01
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多