1. 程式人生 > >C++猜數字遊戲的程式,用srand()函式產生隨機數

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>

執行截圖如下: