我一直致力于计算用户输入平均值的程序。我还无法弄清楚输入检查器的用途。我还不能使用数组或字符串。如何检查两个输入都是数值?如果他们不是;我该如何再次询问正确的输入?
#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;
}
答案 0 :(得分:0)
您可以使用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
。例如
double x = numeric_limits<double>::min();
cin >> x;
cin.clear();
cin.ignore(0xFFFF, '\n');
if (x == numeric_limits<double>::min())
{
cout << "Input incorrect" << endl;
continue;
}
如果发生错误,则x
保持不变,您知道存在错误,因为用户不太可能输入匹配numeric_limits<double>::min()
的数字
与此问题无关,但您还应考虑除以零错误。
if (input == 0)
mean = 0;//avoid divide by zero, print special error message
else
mean = accumulator / input;