我正在从我的 C++ 书中进行随机练习,因为我正在“重新学习”C++,但是我从我编写的程序中得到了一些奇怪的输出。我相当确定程序的逻辑没有错误,但是“scoreCount”数组中元素的总和应该是26,与scores数组的长度相同,它只有20。我可以不知道其他 6 个元素发生了什么。练习的描述在下面的代码中。谁能发现我可能做错了什么?
/* 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;
}
谢谢你的帮助!