[英]how would i make this code loop a certain amount of times only using if else statements (no for, do/while,etc.)? (c++)
今天,我们要分配随机数字游戏。 老师告诉我们,我们只能使用到目前为止所学到的东西。 我们没有学习任何循环,所以我只能使用if / else。 我如何仅使用if / else语句使随机数游戏循环8次并在8结束时显示答案?
我开始这段代码,但对如何继续一无所知。
int main(){
int Guess;
cout << "Guess my number!\n\n";
cout << "Enter a number between 1 and 100. \n";
cin >> Guess;
unsigned Number = time(0);
const int Min = 1, Max = 100;
srand(Number);
Number = (rand() % (Max - Min + 1)) + Min;
int tries = 8;
if (Guess < Number && tries > 0){
tries -= 1;
cout << "guess is lower than the number! try again. tries:" << tries << endl;
cin >> Number;
}
else if (Guess > Number&& tries>0){
tries -= 1;
cout << "guess is higher than the number! try again. tries:" << tries << endl;
cin >> Number;
}
else{
cout << "your answer is right the number is:" << Number << endl;
}
if (tries == 0){
cout << "number is: " << Number << endl;
system("pause");
return 0;
}
system("pause");
return 0;
}
如果/线性非常线性,我不认为您真的可以回到使用它们的开始,也许您的老师表示您可能必须重复相同的行8次,这似乎有点多,但是如果您将代码更简单,这可能很简单,您是否必须告诉玩家他们的猜想是更大还是更小,也许您可以给他们8次尝试,让他们猜测1到20之间的数字,我认为没有while / for循环这样做不是一个好习惯,如果您仅使用循环,它将使一切变得更简单。
我认为没有任何方法可以使用if-else
块进行循环。 我猜你的老师正在给你这个练习,这样你就可以欣赏循环了。 无论如何,这是一个使用开关盒的简洁解决方案。
int main() {
int Guess;
cout << "Guess my number!\n\n";
cout << "Enter a number between 1 and 100. \n";
cin >> Guess;
unsigned Number = time(0);
const int Min = 1, Max = 100;
srand(Number);
Number = (rand() % (Max - Min + 1)) + Min;
int tries = 8;
switch (tries) {
case 8:
if (Guess == Number) {
cout << "your answer is right the number is:" << Number << endl;
break;
} else if (Guess < Number) {
cout << "guess is lower than the number! try again. tries:" << tries << endl;
} else {
cout << "guess is higher than the number! try again. tries:" << tries << endl;
}
cin >> Guess;
tries--;
case 7:
if (Guess == Number) {
cout << "your answer is right the number is:" << Number << endl;
break;
} else if (Guess < Number) {
cout << "guess is lower than the number! try again. tries:" << tries << endl;
} else {
cout << "guess is higher than the number! try again. tries:" << tries << endl;
}
cin >> Guess;
tries--;
// repeat code
case 1:
if (Guess == Number) {
cout << "your answer is right the number is:" << Number << endl;
break;
} else if (Guess < Number) {
cout << "guess is lower than the number! try again. tries:" << tries << endl;
} else {
cout << "guess is higher than the number! try again. tries:" << tries << endl;
}
cin >> Guess;
tries--;
default:
if (Guess == Number) {
cout << "your answer is right the number is:" << Number << endl;
} else {
cout << "number is: " << Number << endl;
}
}
system("pause");
return 0;
}
由于我真的不知道您在课堂上所学的内容,因此只列出了一些选项。 有许多种“循环”:
goto
循环。 for
循环 while
循环 do {} until
循环 main()
从内main()
和使用参数,或者全局或static
的计数器变量。 请记住,也有可能您错过了课堂上快速涵盖的内容,而这些内容不在第1-4章中。 您说:在课堂上或书中都有涉及。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.