我被赋予了使用C ++创建20个问题游戏的任务,其中用户认为1到100之间的数字然后计算机会猜测它。为了做到这一点,我一直在努力学习如何使用switch语句,因为我觉得这将在我的主代码中帮助我。但是,我似乎无法让它解决代码中非法中断的持续错误。我已经尝试更改代码并在线查找答案,但我找不到任何答案。我的代码如下:
#include <iostream>
using namespace std;
int main()
{
int i;
cout << "Enter an integer: ";
cin >> i;
switch (int i)
{
case i > 1 :
{
cout << "int greater than 1, less than 5"; endl;
break;
}
case i > 5 :
{
cout << "int greater than 5 less than 10"; endl;
break;
}
case i > 10 :
{
cout << "int greater than 10"; endl;
break;
}
}
system("PAUSE");
return 0;
}
显示的错误是:
error C2043: illegal break
如果有人能帮助我回答为什么这些错误继续显示会非常感激!
答案 0 :(得分:1)
您不应该将变量i
重新声明为int
,您可以将其传递给
switch (i)
此外,对于switch
来说,这并不是一个很好的用例,因为您需要:
switch (i)
{
case 2:
case 3:
case 4:
case 5:
{
cout << "int greater than 1, less than 5" << endl;
break;
}
case 6:
case 7:
case 8:
case 9:
case 10:
{
cout << "int greater than 5 less than 10" << endl;
break;
}
///...etc
}
您应该真正使用if
,else if
,else
,例如:
if (i > 1 && i < 5)
{
cout << "int greater than 1, less than 5" << endl;
}
else if (i >= 5 && i < 10)
{
cout << "int greater than 5 less than 10" << endl;
}
else if (i >= 10)
{
cout << "int greater than 10" << endl;
}
else
{
cout << "int less than 2" << endl;
}
您的cout
语句也不正确
cout << "int greater than 1, less than 5"; endl;
他们应该
cout << "int greater than 1, less than 5" << endl;