编写一个程序,该程序继续要求用户输入5个以外的任何数字,直到用户输入数字5。然后告诉用户"嘿!您不应该输入5!"并退出程序。
★修改程序,以便在10个迭代后,如果没有输入用户,则5会告诉用户"哇,您的耐心比我更耐心了,您会赢。"和退出。
★★修改程序,以便它要求用户输入以外的任何数字以外的任何数字,等于被要求输入数字的次数。(即,在第一次迭代中"请输入0"以外的任何数字",然后在第二个迭代中输入1英寸M等以外的任何数字等。当用户输入他们被要求的号码时,该程序必须相应地退出到。)
我有大部分程序可以使用。我将其提高到一个地点,要求从0开始并上升,它在10次尝试后向用户提供了患者的消息,如果他们输入不应该使用的数字,则将其退出程序。然而
我真的不知道要搜索什么来解决此问题。但是,我试图移动一些东西,并摆脱了一些冗余变量。
任何提示都将不胜感激,请不要给我答案!这是我到目前为止所拥有的。
#include <iostream>
int main()
{
const int GUESS = 1; // constant for number of tries
const int PATIENCE = 10; // constant for message at 10 tries
int UserNum; // player input
int InputNum = GUESS; // intializes GuessNumber
// asks for player input
do
{
std::cout << "Enter any number other then "<< InputNum << ": ";
std::cin >> UserNum;
// exits program if user inputs the number displayed
if (UserNum == InputNum)
{
std::cout << "Hey! you weren't supposed to enter " << InputNum << "!n";
}
// increase the Guess counter if they dont enter the number displayed
else if (UserNum != InputNum)
{
InputNum++;
}
if (InputNum == PATIENCE)
{
std::cout << "Wow, you're more patient then I am, you win.n";
break;
}
} while (UserNum != InputNum);
return 0;
}
您的问题在do while
循环条件
首先执行语句,并在以后检查条件
例如
InputNum
初始化为1
因此,如果您输入 2
作为用户的输入,在else if
条件下,InputNum
将会增加到2
评估此条件
while (UserNum != InputNum)
它将是错误的,为2==2
循环断裂
解决方案
更改PATIENCE = 11
并使用
while (1)
// this will run infinitely but it will break after 10 iteration or when u press the same number which u shouldn't
而不是
while (UserNum != InputNum)
完整程序
#include <iostream>
int main()
{
const int GUESS = 1; // constant for number of tries
const int PATIENCE = 11; // constant for message at 10 tries
int UserNum; // player input
int InputNum = GUESS; // intializes GuessNumber
// asks for player input
do
{
std::cout << "Enter any number other then " << InputNum << ": ";
std::cin >> UserNum;
// exits program if user inputs the number displayed
if (UserNum == InputNum)
{
std::cout << "Hey! you weren't supposed to enter " << InputNum << "!n";
break;
}
// increase the Guess counter if they dont enter the number displayed
else if (UserNum != InputNum)
{
InputNum++;
}
if (InputNum == PATIENCE)
{
std::cout << "Wow, you're more patient then I am, you win.n";
break;
}
} while (1);
system("pause");
return 0;
}
嘿,尝试此程序,它确实可以完成您想要的。
#include <iostream>
int main ()
{
int GUESS = -1; //loop variable
const int PATIENCE = 10; // constant for message at 10 tries
int InputNum; // input from user
std::cout << "PATIENCE Test" << "!n";
do
{
GUESS++;
// asks for player's input
std::cout << "Enter any number other than " << GUESS << ": ";
std::cin >> InputNum;
// exits program if user inputs the number displayed
if (GUESS == InputNum)
{
std::
cout << "Hey! you weren't supposed to enter " << GUESS << "!n";
break;
}
if (GUESS == PATIENCE)
{
std::cout << "Wow, you're more patient then I am, you win.n";
break;
}
}
while (GUESS != InputNum);
return 0;
}