/*
编写一个猜数字游戏的程序:程序随机选择一个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>
运行截图如下:
标签:Random,cout,srand,number,guss,cin,while,C++,随机数 From: https://blog.51cto.com/u_15907770/5926134