C++ 数字输入检查器的IF或WHILE

C++ 数字输入检查器的IF或WHILE,c++,if-statement,C++,If Statement,我一直在做一个程序,计算用户输入的平均值。我还不知道输入检查器要用什么。我还不能使用数组或字符串。如何检查两个输入是否都是数值?如果不是;如何再次请求正确的输入 #include <iostream> using namespace std; int main() { // Get number from user int input = 0; double accumulator = 0; double mean; cout <<

我一直在做一个程序,计算用户输入的平均值。我还不知道输入检查器要用什么。我还不能使用数组或字符串。如何检查两个输入是否都是数值?如果不是;如何再次请求正确的输入

#include <iostream>
using namespace std;
int main()
{
    // Get number from user
    int input = 0;
    double accumulator = 0;
    double mean;
    cout << "How many numbers would you like me to average together?\n";
    cin >> input;
    if (input >= 0){ //to check if input is a numerical value

        // Compute and print the mean of the user input

        int number = 1;
        double x;
        while (number <= input) //while corrected
        {
            cout << "Please type a numerical value now: \n";
            cin >> x;
            if (x < 0  || x > 0){ //to check if x is a numerical value
                accumulator = accumulator + x;
            }
            else {
                cout << "Input incorrect"<< endl;
            }
            number = number + 1;
        }
        mean = accumulator / input; // formula corrected
        cout << "The mean of all the input values is: " << mean << endl;
        cout << "The amount of numbers for the average calculation is: " << input << endl;
        }
    else {
        cout << "Input incorrect"<< endl;
    }
    return 0;
}
#包括
使用名称空间std;
int main()
{
//从用户处获取号码
int输入=0;
双累加器=0;
双均值;
cout>输入;
如果(输入>=0){//检查输入是否为数值
//计算并打印用户输入的平均值
整数=1;
双x;
而(x,;
如果(x<0 | | x>0){//检查x是否为数值
累加器=累加器+x;
}
否则{

cout您可以使用
cin.fail
检查错误。请注意,如果用户输入一个后跟字母的数字,比如
123abc
,则
x
将存储为
123
,但
abc
仍保留在输入缓冲区中。您可能希望立即清除该错误,以便
abc
不会出现在下一个循环中

while (number <= input) //while corrected
{
    cout << "Please type a numerical value now: \n";
    cin >> x;

    bool error = cin.fail();
    cin.clear();
    cin.ignore(0xFFFF, '\n');

    if (error) 
    { 
        cout << "Input incorrect" << endl;
        continue;
    }

    accumulator = accumulator + x;
    number = number + 1;
}
如果出现错误,则
x
将保持不变,并且您知道有错误,因为用户不太可能输入与
numeric\u limits::min()匹配的数字

与此问题无关,但您还应说明被零除的错误

if (input == 0)
    mean = 0;//avoid divide by zero, print special error message
else
    mean = accumulator / input; 

我的猜测:如何检查用户输入(表示为整数)是否有效?请参阅
if (input == 0)
    mean = 0;//avoid divide by zero, print special error message
else
    mean = accumulator / input;