从计数和平均值中忽略无效输入

时间:2018-11-12 03:46:29

标签: c++ loops boolean

程序要求用户输入数字,完成后需要输入负数退出循环。然后,程序将输出数字的平均值和数字的计数。负数应从系列中删除。因此,如果我们有三个数字并退出(第四个)负数,则平均值将仅是三个数字中的一个,而不包括负数。整洁,我以某种方式完成了这项工作。现在,我需要对此进行扩展,以便也可以使用布尔方程将输入验证为整数且小于100。正是在这一点上,我无法确定如何从结果中排除错误的输入。

#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    float inScore= 1;
    float sumScore= 0.0;
    int scoreCount= 0;
    float avgScore= 0.0;
    bool moreNumbers = true;
    bool notNumbers = true;


    for ( inScore =1; inScore >=1; inScore++)  //for loop some kind of blackmagic not really sure about this right now
    {
        cout << "Please enter grades (enter a negative integer to exit): ";
        cin >> inScore;
        if (!cin || inScore > 100)
        {
            notNumbers = false;  //boolean to ignore non integers or numbers greater than 100
            cin.clear();
            cin.ignore(256, '\n');
            scoreCount--;
            cout << "Invalid number!" << endl;
        }         //something is wrong in this section and I can't get it to ignore the invalid inputs

        else if (inScore < 0)
        {
            moreNumbers = false;
        }         //breaks the loop upon a negative number being entered
        else
            sumScore+=inScore;
        scoreCount++;
    }
    avgScore = (sumScore+=inScore)/(scoreCount-1);
    cout << "Number of Grades: " << scoreCount-1 << endl;  //number of entries
    cout << "Average: " << avgScore << endl;                // average grade except I cannot figure out how to remove negative number from the array

    return 0;
}

0 个答案:

没有答案