本文主要是介绍C++猜数字游戏的程序,用srand()函数产生随机数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/*编写一个猜数字游戏的程序:程序随机选择一个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()函数产生随机数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!