为什么计数器不起作用

时间:2013-12-13 00:33:06

标签: c++

我正在努力帮助一个朋友,我似乎无法得到它们。我不知道为什么但几个变量没有正确显示。

我把它撞到了我认为问题的地方,但我不知道如何解决它。

#include <iostream>
#include <fstream>
using namespace std;
int main() 
{
//declaring variables
ifstream myfile("input.txt");
double grades[26];
unsigned scores[8] = {0};




//getting data from text file
    for(int i=0; i<26; i++)
        {
            myfile >> grades[i];
            cin.ignore();


    if((grades[i] >= 175) && (grades[i] <= 200)) scores[7]++; 
    else if(grades[i] >= 150)                    scores[6]++;
    else if(grades[i] >= 125)                    scores[5]++;
    else if(grades[i] >= 100)                    scores[4]++;
    else if(grades[i] >= 75)                     scores[3]++;
    else if(grades[i] >= 50)                     scores[2]++;
    else if(grades[i] >= 25)                     scores[1]++;
    else if(grades[i] >= 0)                      scores[0]++;
      }

//outputing results


for(int z = 0; z < 200; z += 25)
{
    if(z == 175)
        cout << "Number of students between 175 and 200: " << scores[z] << endl;
    else
        cout << "Number of students between " << z << " and " << z + 24 << ": " << scores[z]<< endl;
}

return 0;
}

它从中提取的文件中有这个。

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

我知道问题出在

的某个地方
//getting data from text file
    for(i=0; i<26; i++)
        {
            myfile >> grades[i];
            cin.ignore();

我不知道该怎么做才能修复它,我不知道它为什么会被打破。

输出

   Number of students between 0 and 24: 25
Number of students between 25 and 49: 32767
Number of students between 50 and 74: 3900547712
Number of students between 75 and 99: 0
Number of students between 100 and 124: 0
Number of students between 125 and 149: 32760
Number of students between 150 and 174: 0
Number of students between 175 and 200: 32767

当输出应该是。
0-24:12之间的学生人数

我不知道为什么它不能正常工作。 感谢让我知道将输出放在这里......忘了。

2 个答案:

答案 0 :(得分:5)

我不知道你想要什么,但仅仅是因为我们:

double score1, score2, score3, score4, score5, score6, score7, score8 = 0.0;

此行只会将score8初始化为0。

答案 1 :(得分:3)

您可以采取一些措施来提高代码的可读性,从而更容易发现逻辑错误......

为什么不将分数变量设为数组?其次,为什么要使用double?这不是必要的,是吗?

unsigned scores[8] = {0};

为什么这么多if?一旦发现某个值在一定范围内,为什么还要继续查看它是否在您知道它不能的范围内?

if((grades[i] >= 175) && (grades[i] <= 200)) scores[7]++; 
else if(grades[i] >= 150)                    scores[6]++;
else if(grades[i] >= 125)                    scores[5]++;
else if(grades[i] >= 100)                    scores[4]++;
else if(grades[i] >= 75)                     scores[3]++;
else if(grades[i] >= 50)                     scores[2]++;
else if(grades[i] >= 25)                     scores[1]++;
else if(grades[i] >= 0)                      scores[0]++;

您可以使用数组输出结果:

for(int i = 0; i < 8; i++)
{
    if(i == 7)
        cout << "Number of students between 175 and 200: " << score[i] << endl;
    else
        cout << "Number of students between " << (i * 25) << " and " << (i * 25 + 24) << ": " << score[i] << endl;
}