为什么如果我输入任何字母,我的代码会说它属于区间 -1, 1 而不是移动到 else 子句并打印错误消息?
#include <iostream>
using namespace std;
int main()
{
double x ;
cout << "Enter a real number : " ;
cin >> x ;
if ((x >= -1) && (x < 1)) {
cout << "The nunber you have entered is valid and lies in the interval -1,1!" << endl;
}
else if ((x < -1) || (x >= 1)) {
cout << "Unfortunetely the number you entered is valid but does not lie in the interval" << endl;
}
else {
cout << "Error you have not entered a valid real number!" << endl;
}
return 0;
}
从用户输入中读取的double
总是在(-1,1]
内或不在里面。没有第三种选择。当用户输入无法解析为double
的内容时,0
将分配给x
。如果要检查输入失败,则应检查流的状态。例如,您可以通过将其转换为if
内的bool
来做到这一点:
#include <iostream>
using namespace std;
int main()
{
double x ;
cout << "Enter a real number : " ;
if (cin >> x) { // <--- if reading x succeded
if ((x >= -1) && (x < 1)) {
cout << "The nunber you have entered is valid and lies in the interval -1,1!" << endl;
} else if ((x < -1) || (x >= 1)) {
cout << "Unfortunetely the number you entered is valid but does not lie in the interval" << endl;
}
} else {
cout << "Error you have not entered a valid real number!" << endl;
}
return 0;
}
如果您想在之后阅读更多内容,则必须在之前重置流的失败状态。
PS:浮点数不是实数,它们都是有理数。