我必须编写一个程序来运行随机猜谜游戏。游戏的数字是从 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;
}
[编辑:添加强制转换以消除编译器警告。]
正如吉姆·罗兹(Jim Rhodes)在评论中所说,问题在于这条线
srand(number>0);
srand() http://www.cplusplus.com/reference/cstdlib/srand/用于初始化随机数生成器,因此用它来调用它是没有意义的number>0
,或者甚至与number
根本不。它需要一个“种子”值,每次运行程序时该值都应该不同。获取此类种子的常见方法是使用系统时间:
srand(static_cast<unsigned int>(time(NULL)));
你可能需要#include
要访问的另一个标头time() http://www.cplusplus.com/reference/ctime/time/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)