我目前正在我的学校学习C / C ++编程课程。我的任务是编写一段代码,询问用户他们想要平均多少个数字,然后对它们求平均值。该程序必须包含一个for循环。我遇到的问题是,在用户输入“n”变量后,如果他们输入了诸如“a”之类的字符,程序将立即吐出答案作为我的平均值。我想找到一种方法来阻止用户输入字符,以便我的for循环可以完成运行并正确平均数字。这是我的代码:
{
int n, i = 1, x = 1;
double sum = 0, average, value;
cout << "\nHow many numbers do you want to average?: ";
cin >> n;
while (n < 1)
{
cout << "\nYou have entered an invalid number.\n";
cout << "\nHow many numbers do you want to average?: ";
cin.clear();
while (cin.get() != '\n');
cin >> n;
}
for (n; i <= n; i++)
{
cout << "\nEnter value: ";
cin >> value;
sum = sum + value;
}
average = sum / n;
cout << "\nThe average is: " << average << endl;
system("pause");
return 0;
}