问题是当用户输入 = 9999999999 时,控制台将返回所有值。如果有人试图为 a, b = 9999999999 设置值,我想通过使用简单的else if语句来限制此输入,那么用户必须收到我在代码中定义的警告。我可以通过使用 double 而不是 int 来控制它,但这不是解决方案。
#include <iostream>
using namespace std;
main()
{
int a, b, c, d;
cout << "Enter Value for A: ";
cin >> a;
cout << "Enter Value for B: ";
cin >> b;
if (a > b)
{
cout << "A is Greater than B " << endl; //This will be printed only if the statement is True
}
else if ( a < b )
{
cout << "A is Less than B " << endl; //This will be printed if the statement is False
}
else if ( a, b > 999999999 )
{
cout << " The Value is filtered by autobot !not allowed " << endl; //This will be printed if the statement is going against the rules
}
else
{
cout << "Values are not given or Unknown " << endl; //This will be printed if the both statements are unknown
}
cout << "Enter Value for C: ";
cin >> c;
cout << "Enter Value for D: ";
cin >> d;
if (c < d)
{
cout << c << " < " << d << endl; //This will be printed if the statement is True
}
else if ( c > d )
{
cout << "C is Greater than D " << endl; //This will be printed if the statement is False
}
else
{
cout << c << " unknown " << d << endl; //This will be printed if the statement is Unknown
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个确保有效输入的示例函数。我也让它接受了最小值和最大值,但你不一定需要它们,因为 999999999int无论如何都会超出范围,这会导致cin失败。不过它会等待有效的输入。
int getNum( int min, int max ) {
int val;
while ( !( cin >> val ) || val < min || val > max ) {
if ( !cin ) {
cin.clear();
cin.ignore( 1000, '\n' );
}
cout << "You entered an invalid number\n";
}
return val;
}
int main() {
int a = getNum( 0, 12321 );
}
Run Code Online (Sandbox Code Playgroud)
编辑:嗯,现在你刚刚修改了你的问题,使用简单的 else if 语句,改变答案。那么答案是否定的。由于cin会失败,您实际上无法进行检查。此外,它永远不会是真的,因为999999999它比INT_MAX我能想到的任何实现都要大。
| 归档时间: |
|
| 查看次数: |
341 次 |
| 最近记录: |