数组预增量
Pre increment on arrays
谁能解释这段代码的输出?一直在敲我的脑袋,真的很难理解,就是不明白。
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 responses[] = new int[4];
responses[0] = 1;
responses[1] = 2;
responses[2] = 4;
responses[3] = 4;
int freq[] = new int[5];
for(int answer = 1; answer < 4; answer++)
{
int x = responses[answer];
freq[x] = freq[x] + 1;
}
for (int rating = 1; rating < 5; rating++)
{
//Print 6 spaces and then the rating variable
//Print 10 spaces then the integer at freq[rating]
System.out.printf("%6d%10d\n", rating, freq[rating]);
}
我会查找 ++ prefix & postfix。
在第一个循环中 ++freq[responses[answer]];意思是:
- responses[answer] 从响应数组索引中获取值。
- Freq[value] 检查并从 Filter 数组索引中获取值。
- ++Freq[value] 将值 1 添加到 Freq[value]。
谁能解释这段代码的输出?一直在敲我的脑袋,真的很难理解,就是不明白。
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 responses[] = new int[4];
responses[0] = 1;
responses[1] = 2;
responses[2] = 4;
responses[3] = 4;
int freq[] = new int[5];
for(int answer = 1; answer < 4; answer++)
{
int x = responses[answer];
freq[x] = freq[x] + 1;
}
for (int rating = 1; rating < 5; rating++)
{
//Print 6 spaces and then the rating variable
//Print 10 spaces then the integer at freq[rating]
System.out.printf("%6d%10d\n", rating, freq[rating]);
}
我会查找 ++ prefix & postfix。
在第一个循环中 ++freq[responses[answer]];意思是:
- responses[answer] 从响应数组索引中获取值。
- Freq[value] 检查并从 Filter 数组索引中获取值。
- ++Freq[value] 将值 1 添加到 Freq[value]。