gpt4 book ai didi

java - 数组上的预增量如何工作

转载 作者:行者123 更新时间:2023-12-01 11:13:38 26 4
gpt4 key购买 nike

++frequency[2] ;

我认为未初始化的数组的默认值是0。Imo,这意味着评估频率[2] 为零,然后加 1 并将其分配给索引 2。请任何人解释一下如何获得此代码的输出。这件事让我很头疼。

 public static void main(String ars[])
{

int responses[] = {1,2,4,4};
int freq[] = new int[5];
for(int answer = 1;answer < responses.length;answer++){
++freq[responses[answer]];
}
for ( int rating = 1; rating < freq.length; rating++ )
System.out.printf( "%6d%10d\n", rating, freq[ rating ] );

//输出

     1         0
2 1
3 0
4 2

最佳答案

是的,你是。

int[] frequency = new int[3];
System.out.println(frequency[2]);
System.out.println(++frequency[2]);
System.out.println(frequency[2]);

打印:

0
1
1

编辑:正如潜伏者在这里所说的How does this pre increment on arrays work ,这个答案对 Java 有效,但可能不适用于其他语言。

关于java - 数组上的预增量如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32100474/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com