[更新]我在C ++中具有以下代码(跳过不必要的详细信息):
#include <iostream>
using namespace std;
int main() {
double value;
double sum = 0;
double max, min;
string msg = "Enter next value (-1) to end: ";
int validCounter = 0;
do{
cout << msg;
cin >> value; // Values assumed to be numbers
}
while (value <= 0 and value != -1);
if (value > 0.0){sum+= value, max = value, min = value, validCounter = 1;} // Initial values of min, max, validCounter = 1
while (value != -1){
cout << msg;
cin >> value;
// Only take positive values into consideration for stats
if (value > 0) {
validCounter++;
sum += value;
if (value > max) { max = value; }
if (value < min) { min = value; }
}
}
cout << to_string(validCounter) + " valid value(s) entered" << endl;
if (validCounter > 0){
cout << "Minimum: " + to_string(min) << endl;
cout << "Maximum: " + to_string(max) << endl;
cout << "Moyenne: " + to_string(sum/validCounter) << endl;
}
return 0;
}
但是,如果提示输入值(为简单起见,它是一个数字,这是一个初学者程序),如果输入的值不是double值,则while循环开始无限显示输入提示。为什么是这样?是否由于比较String!= -1(或任何其他非int / double类型)导致循环重复的事实?我在这里很困惑。
答案 0 :(得分:4)
替换
do{
cout << msg;
cin >> value; // Values assumed to be numbers
}
while (value <= 0 and value != -1);
作者
do {
cout << msg;
if (!(cin >> value)) {
string dummy;
cin.clear(); // to be able to read double
cin >> dummy; // to remove the non float
value = 0;
}
while (value <= 0 and value != -1);
您需要清除错误才能再次读取,然后绕过错误的输入,也许您也可以只读取一个字符,并确定出现错误时的处理方法
示例:
#include <iostream>
using namespace std;
int main()
{
double value;
do {
cout << "value please" << endl;
if (!(cin >> value)) {
string dummy;
cin.clear();
cin >> dummy;
value = 0;
}
} while (value <= 0 and value != -1);
cout << "valid double :" << value << endl;
return 0;
}
编译和执行:
% ./a.out
value please
aze
value please
-12
value please
12
valid double :12