我想要的是让用户猜测数字的次数,然后告诉他猜测它的次数,这就是为什么我要为for loop g!= r,但是,我不知道C ++是否允许这样做。
此外,我在尝试编译时遇到的错误是
expression must have a constant value
expression did not evaluate to a constant" and "case expression not constant
这是代码:
int main()
{
int r = rand() % 101;
int g = 0;
int t = 10;
std::cout << "Guess a number, human (From 1 to 100)." << std::endl;
std::cin >> g;
for (int t = 0; g != r; t++)
{
switch (g) {
case (g == r):
std::cout << "You won, now get lost!" << std::endl;
break;
case (g < r):
std::cout << "Too low, piece of turd." << std::endl;
break;
case (g > r):
std::cout << "Too high, dubai." << std::endl;
break;
default :
std::cout << "How could you possibly have gotten it wrong, you stupid ape." << std::endl;
}
}
std::cout << "Finally!, it took you " << t << " freaking times!" << std::endl;
return 0;
}
答案 0 :(得分:3)
切换案例检查必须是常量表达式,与原始值进行相等性比较。
在您的情况下,您可以使用 if 命令重写开关。 使用下面的代码,它将编译。
if (g == r)
{
std::cout << "You won, now get lost!" << std::endl;
}
else if (g < r)
{
std::cout << "Too low, piece of turd." << std::endl;
}
else if (g > r)
{
std::cout << "Too high, dubai." << std::endl;
}
else
{
// will not get here, as previous if already cover all cases
std::cout << "How could you possibly have gotten it wrong, you stupid ape." << std::endl;
}
答案 1 :(得分:0)
如果您需要使用交换机,您可以尝试在切换之前使用带有标志的while循环和一些检查:
bool flag = true;
int t = 0;
int x = 0;
while( flag )
{
t++;
std::cout << "Guess a number, human (From 1 to 100)." << std::endl;
std::cin >> g;
if( g == r )
{
x = 1;
flag = false;
}
else if( g < r )
x = 2;
else
x = 3;
switch (x) {
case (1):
std::cout << "You won, now get lost!" << std::endl;
break;
case (2):
std::cout << "Too low, piece of turd." << std::endl;
break;
case (3):
std::cout << "Too high, dubai." << std::endl;
break;
default :
std::cout << "How could you possibly have gotten it wrong, you stupid ape." << std::endl;
}
}
答案 2 :(得分:0)
我将其更改为 if 语句,现在在第一次猜测之后,用户无法再次猜测。
好的,这里有新代码:int main()
{
<!DOCTYPE html>
<html>
<head>
<script>
function loadList() {
var xhttp;
var x = document.getElementById("x").value;
var y = document.getElementById("y").value;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("table").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "list.php?x="+x+"&y="+y, true);
xhttp.send();
}
</script>
</head>
<body>
<form action="">
<input type="text" id="x"> <br>
<input type="text" id="y"> <br>
<input type="button" value="Find" onclick="loadList()">
</form>
<div id="table"> </div>
</body>
</html>
}