### 迭代数组时有些数据未计入

``````/* Exercise 09 - 04

Write a program that reads a file consisting of students' test scores
in the range 0-200. It should then determine the number of students having
scores in each of the following ranges: 0-24, 25-49, 50-74, 75-99,
100-124, 125-149, 150-174, and 175-200. Output the score ranges and the
number of students. (Run your program with the following input data:
76, 89, 150, 135, 200, 76, 12, 100, 150, 28, 178, 189, 167, 200, 175,
150, 87, 99, 129, 149, 176, 200, 87, 35, 157, 189.) */
#include <cstdio>

int main(int argc, char ** argv) {
int scores[] = {76, 89, 150, 135, 200, 76, 12, 100, 150, 28, 178, 189,
167, 200, 175, 150, 87, 99, 129, 149, 176, 200, 87,
35, 157, 189};
int size = sizeof(scores) / sizeof(scores[0]);
int scoreCount[] = {0, 0, 0, 0, 0, 0, 0, 0};

printf("Number of Scores: %d\n\n", size);

for(int i = 0; i < size; i++) {
scoreCount[((int)(scores[i]/25))] += 1;
printf("%d - scoreCount Index: %d\n", i, ((int)(scores[i]/25)));
}

printf("\n");

int low = 0;
int high = 24;

size = sizeof(scoreCount) / sizeof(scoreCount[0]);

for(int i = 0; i < size; i++) {
printf("Range %d-%d: %d\n", low, high, scoreCount[i]);
low += 25;
high += 25;
if(high == 199) high = 200;
}

int sum = 0;

for(int i = 0; i < size; i++) {
sum += scoreCount[i];
}

if(sum < 26) printf("\n%d: Wrong number of scores counted.\n", sum);
else printf("\nAll students accounted for.\n");

return 0;
}
``````

#### 8 个答案:

``````#include <vector>
#include <map>
#include <iostream>

int main(int argc, char ** argv)
{
const std::vector<int> scores = {76, 89, 150, 135, 200, 76, 12, 100, 150, 28, 178, 189,
167, 200, 175, 150, 87, 99, 129, 149, 176, 200, 87,
35, 157, 189
};
std::map<int, int> scoreCount;
std::cout << "Number of Scores: " << scores.size() << "\n";

for(auto score : scores)
{
scoreCount[score/25] ++;
std::cout <<  score << " - scoreCount Index: " << score/25 << "\n";
}

for(auto const& slot : scoreCount)
{
auto low  = slot.first*25;
auto high = low+24;
std::cout << "Range " << low << "-" << high << ": " << slot.second << "\n";
}

int sum = 0;
for(auto const& slot : scoreCount)
sum += slot.second;

if(sum < 26)
printf("\n%d: Wrong number of scores counted.\n", sum);
else
printf("\nAll students accounted for.\n");
}
``````

``````  scoreCount[((int)(scores[i]/25))] += 1;
``````

200/25 = 8和 scoreCount [8]不存在。

``````scoreCount[((int)(scores[i]/25))] += 1;
``````

`scoreCount`的有效索引来自`0 to 7`，但对于您当前的`scores`，您将生成最多`8`的索引。解决方案是将`scoreCount`扩展一个元素或检查索引是否为`8`并将其映射到索引`7`，因为问题似乎限制了您的范围。

scoreCount数组中元素的数量应为9而不是8。

``````scoreCount[(scores[i]/25)==8?7:(scores[i]/25)] += 1;
``````

200/25 = 8超出了scoreCount的范围 - 只有索引0 - 7。

``````for(int i = 0; i < size; i++){
int theIndex = (scores[i]/25);
if(theIndex == 8)
scoreCount[7] += 1;
else
scoreCount[theIndex] += 1;
printf("%d - scoreCount Index: %d\n", i, theIndex;
}
``````