概述
/*
编写一个猜数字游戏的程序:程序随机选择一个1到1000的数,然后输出:
I have a number between 1 and 1000.
Can you guess my number?
Please type your first guess:
接着,游戏者输入一个结果。程序根据比较结果输出以下三条信息之一:
1)Excellent! You guessed the number!
Would you like to play again (y or n)?
2)Too low.Try again.
3)Too high.Try again.
如果游戏者猜错,则程序进行循环,直到猜对。程序通过Too high或Too low消息帮助学生接近正确答案。请思考:怎样才能猜得最快?
*/
<span style="font-size:14px;">#include<iostream>
#include <cstdlib>
#include<time.h>
using namespace std;
int RNG() //此函数用于产生随机数
{
int Random_number;
srand(time(0));<span style="white-space:pre"> </span>//获取系统时间来作为种子
Random_number=1+rand()%1000;
return Random_number;
}
int main()
{
int Random_number,guss_number;
char yes_no;
while(true)
{
Random_number=RNG();
cout<<Random_number<<endl;//输出系统产生的随机数,免得难得猜。
cout<<"I have a number between 1 and 1000"<<endl;
cout<<"Can you guess my number?"<<endl;
cout<<"Please type your first guess:";
cin>>guss_number;
while(guss_number<1||guss_number>1000)
{
cout<<"Input error,once again!";
cin>>guss_number;
}
while(true)
{
if(guss_number==Random_number)
{
cout<<"Excellent! You guessed the number!"<<endl;
cout<<"Would you like to play again (y or n)?:" ;
cin>>yes_no;
if(yes_no=='n')
{
exit(0); //返回操作系统
}
else
{
break; //跳出第一层循环
}
}
if(guss_number<Random_number)
{
cout<<"Too low.Try again ";
cin>>guss_number;
while(guss_number<1||guss_number>1000)
{
cout<<"Input error,once again!";
cin>>guss_number;
}
}
if(guss_number>Random_number)
{
cout<<"Too high.Try again ";
cin>>guss_number;
while(guss_number<1||guss_number>1000)
{
cout<<"Input error,once again!";
cin>>guss_number;
}
}
}
}
return 0;
} </span>
运行截图如下:
最后
以上就是迅速鸭子为你收集整理的C++猜数字游戏的程序,用srand()函数产生随机数的全部内容,希望文章能够帮你解决C++猜数字游戏的程序,用srand()函数产生随机数所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复