C ++计数X以上的负数和数字

时间:2014-10-29 23:57:52

标签: c++

我正在开发一个项目,在txt文件中有一个数字列表。 C ++程序正在提取这些数字,并根据它们是否符合某些标准将它们放入适当的“桶”中。我想要小于0的数字和超过200的数字一起放入桶中。但我似乎无法让负数被认可。想法?

//GET IT STARTED IN HERE
int main()
{
//VARIABLES ETC
int score;

//SET SCORE RANGES TO 0
int bucket[9] = {0,0,0,0,0,0,0,0,0};


ifstream scoreFile;
string file;


//OPEN UP THE SCORE FILE
cout << "Enter path to Score File: ";
cin >> file;

scoreFile.open(file.c_str());

if (file == "kill" || file == "KILL" || file == "Kill") {
    cout << "Program terminated with KILL command" << endl;
    return 0;
}
else
{
//CHECK FOR BAD PATH
while (!scoreFile)
{
    cerr << "Wrong path" << endl;
    cout << "Try path again: ";
    cin >> file;
    scoreFile.clear();
    scoreFile.open(file.c_str());
}
}
//LOOK AT ALL THE SCORES FROM LAST WEEKS TEST
int scoreRow(1);

//CHECK EACH ONE AND ADD IT TO THE APPROPRIATE BUCKET
while (scoreFile >> score)
{
    if (score <= 24)
        bucket[0]++;

    else if (score <= 49)
        bucket[1]++;

    else if (score <= 74)
        bucket[2]++;

    else if (score <= 99)
        bucket[3]++;

    else if (score <= 124)
        bucket[4]++;

    else if (score <= 149)
        bucket[5]++;

    else if (score <= 174)
        bucket[6]++;

    else if (score <= 200)
        bucket[7]++;

    //ADDED TWO EXTRA SCORES IN THE FILE TO TEST THIS AREA

    else if (score < 0 || score > 200)
        bucket[8]++;

    scoreRow++;
} 

//OUTPUT SOME RESULTS
cout << endl << "SCORE EVALUATION"<< endl;
cout << "Amount of students who scored    0 - 24: " << bucket[0] << endl;
cout << "Amount of students who scored   25 - 49: " << bucket[1] << endl;
cout << "Amount of students who scored   50 - 74: " << bucket[2] << endl;
cout << "Amount of students who scored   75 - 99: " << bucket[3] << endl;
cout << "Amount of students who scored 100 - 124: " << bucket[4] << endl;
cout << "Amount of students who scored 125 - 149: " << bucket[5] << endl;
cout << "Amount of students who scored 150 - 174: " << bucket[6] << endl;
cout << "Amount of students who scored 175 - 200: " << bucket[7] << endl;
cout << "Scores out of Range: " << bucket[8] << endl;

}

2 个答案:

答案 0 :(得分:2)

您希望将最后一个条件置于顶部。

   //CHECK EACH ONE AND ADD IT TO THE APPROPRIATE BUCKET
    while (scoreFile >> score)
    {
        if (score < 0 || score > 200)
            bucket[8]++;

        else if (score <= 24)
            bucket[0]++;

        else if (score <= 49)
            bucket[1]++;

        else if (score <= 74)
            bucket[2]++;

        else if (score <= 99)
            bucket[3]++;

        else if (score <= 124)
            bucket[4]++;

        else if (score <= 149)
            bucket[5]++;

        else if (score <= 174)
            bucket[6]++;

        else if (score <= 200)
            bucket[7]++;

        scoreRow++;
    } 

答案 1 :(得分:0)

这里的每个分数只能进入一个桶。如果得分< 0,它将由第一个if语句评估并放在该桶中。

所以你的最后一个if if()只会捕获超过200的值,如果你有任何负分,他们将全部落在第一桶。

相关问题