public class ArrayStudentPoll {
public static void main( String args[] )
{
// array of survey responses
int responses[] = { 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6,
10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6,
4, 8, 6, 8, 10 };
int frequency[] = new int[ 11 ]; // array of frequency counters
// for each answer, select responses element and use that value
// as frequency index to determine element to increment
for ( int answer = 0; answer < responses.length; answer++ )
++frequency[ responses[ answer ] ];
System.out.printf( "%s%10s\n", "Rating", "Frequency" );
// output each array element's value
for ( int rating = 1; rating < frequency.length; rating++ )
System.out.printf( "%6d%10d\n", rating, frequency[ rating ] );
}
}
这是我在项目中看到的代码。
我理解的所有内容,但++frequency[i];
部分的频率是数组而不是数字?到底是做什么的?他们写了评论但仍然没有得到它们。
这是我摆脱它的结果
Rating Frequency
1 2
2 2
3 2
4 2
5 5
6 11
7 5
8 7
9 1
10 3
答案 0 :(得分:3)
++frequency[responses[answer]]
预先递增responses[answer]
数组的frequency
'元素。
相当于
frequency[responses[answer]] = frequency[responses[answer]] + 1;
BTW,使用后递增(frequency[responses[answer]]++
)将在此程序中得到相同的结果,因为此代码不使用递增运算符的返回值。