我必须编写一个运行随机猜谜游戏的程序。游戏是从 1 到 100 的数字,猜者有 20 次尝试,最后应该被问到他们是否想再玩一次。如果猜测者是高或低,还必须有多个打印输出选项。我已经完成了我的程序的一部分我知道我仍然需要为打印输出添加其他选项但是现在我的问题是当我尝试运行我所拥有的内容时它说成功但是然后有一个错误说变量“ number" 正在使用而没有被初始化。我不知道该怎么做才能让它初始化。(我是 C++ 新手) 我已经更新了我的程序,现在遇到了不同的问题。我的程序运行,但如果猜测低于它打印的数字太高再试一次,太低再试一次,但是当数字太高时,它只会打印太高再试一次。我还注意到,当用户选择再次玩游戏时,尝试次数计数器不会随着游戏重置。最后一件事我必须添加更多消息,说明他们何时赢、输并被要求玩另一场比赛,我必须使用随机数在其中进行选择。所以任何关于最佳路线的建议都会很棒
#include <iostream>
#include <iomanip>
#include <ctime>
using namespace std;
char chr;
int main()
{
srand(time(NULL)); //the function that generates random numbers
int number=rand()%100+1; //the range of the random numbers
int guess; //The guess is stored here
int tries=0; //The number of tries stored here
char answer; //The answer to the question is stored here
answer='y';
while(answer=='y'||answer=='Y')
{
while (tries<=20 && answer=='y'|| answer=='Y')
{
cout<<"Enter a number between 1 and 100 "<<endl; //The user is asked for a guess
cin>>guess; //The guess is stored here
tries++; //Adding a number for every try
if(guess==0||guess>100) //If statement that produces an error message if user enters a number out of the peramiters
{
cout<<"This is not an option try again"<<endl; //Error message
}
if(tries<20)
cout<<"Tries left: "<<(20-tries)<<endl; //Output to let the user know how many guess they have left
if(number<guess); //if the guess is to high
cout<<"Too high try again"<<endl; //This message prints if guess it to high
if(number>guess) //if the guess is to low
cout<<"Too low try again"<<endl; //This message prints if the guess is to low
if(number==guess) //If the user guesses the number
{
cout<<"Congratualtions!! "<<endl; //Message printed out if the user guesses correctly
cout<<"You got the right number in "<<tries<<" tries"<<endl; //Lets the user know how many guess they used
answer = 'n';
}
if(tries >= 20) //If the user uses all their guesses
{
cout << "You've run out of tries!"<<endl; //The message that prints when a user is out of guesses
answer='n';
}
if(answer=='n')
{
cout<<"Would you like to play again? Enter Y/N"<<endl; //asking if play would like to play again
cin>>answer; //Store users answer
if (answer=='N'|| answer=='n') //if the user says no
cout<<"Thanks for playing!"<<endl; //This message prints out if they choose not to play again
else
number=rand()%100+1; //This starts the game over if they choose to play again
}
}
}
cin>>chr;
return 0;
}