【问题标题】:Array value post-increment数组值后增量
【发布时间】:2016-01-29 15:08:45
【问题描述】:

我一直在研究几个数组示例。一路上取得了一些成功。这几天我一直在研究这段代码,只是无法理解循环体中这个增量的目的。它通常是从它被隔离时开始制作的,但这次我不知道它做了什么。

计算 1 到 10 之间整数的出现次数

Scanner input = new Scanner(System.in);
int[] count = new int[10];

System.out.println("Enter the integers between 1 and 10: ");

// Read all numbers
// 2 5 6 5 4 3 9 7 2 0
for (int i = 0; i < count.length; i++)
{
    int number = input.nextInt();
    count[number]++; //this is the one that perplexes me the most
}

//Display result
for (int i = 0; i < 10; i++) 
{
    if (count[i] > 0) 
    {
        System.out.println(i + " occurs " + count[i]
                + ((count[i] == 1) ? " time" : " times"));
    }
}

【问题讨论】:

  • 欢迎来到 Stack Overflow!这句话“..这次我不知道它做了什么..”是否也意味着你不知道你正在使用什么编程语言?如果你这样做,请edit你的问题,至少为它添加一个标签。只要您这样做,为什么不阅读How do I ask a good question? 并尝试改进一下。
  • count[number]++; //this is the one that perplexes me the most – 这有什么令人困惑的地方?有一个名为count 的数组,对于用户输入的每个数字,相应的数组元素都会加一——这样最后这个数组就可以知道每个数字被用户输入了多少次.
  • 当我看到这样的代码时你会看到 count[number]++;我通常认为向索引添加一个数字是因为它会向前移动而不是你解释它的方式。
  • 当您可以通过 for 循环将 10 个整数添加到数组中时,为什么还要手动输入 1 到 10 之间的整数?我认为该字符串应为“输入 10 个整数”,因为这就是代码实际在做的事情

标签: java arrays increment


【解决方案1】:
count[number]++; //this is the one that perplexes me the most

它在索引number 处增加数组count 中的值。也许,拆分它可能有助于理解:

int tmp = count[number];
tmp = tmp + 1;
count[number] = tmp;

count[number] 的值将在执行count[number]++; 语句之后递增。


还有关于后增量如何工作的说明。

如果它被用作:

int value = count[number]++;

那么value 将具有count[number] 的旧值,并且将在语句执行后完成增量。

【讨论】:

  • 我来这里已经有一段时间了,现在我可以看到问题的答案是多么简单。感谢大家的帮助。
猜你喜欢
  • 2013-05-27
  • 2015-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多