捉鱉程式的實作
- 1、亂數的生成
- 2、反復捉鱉與程式設計
- 3、細節優化
1、亂數的生成
前幾天啊,班里要選人去學那什么健美操,采用捉鱉的方式,我突發奇想能不能用c語言設計個隨機抽號程式,程式的精髓在如何“隨機”,
查閱后,rand函式可以生成亂數,于是先跑起來讓它生成十個亂數并輸出

而后讓它跑第二次

發現和第一次生成的亂數無差別,這不符合我們的需要!
于是我認真地查閱了這個函式,發現它在使用前還需要一個srand函式來設定亂數,
The srand function sets the starting point for generating a series of pseudorandom integers. To reinitialize the generator, use 1 as the seed argument. Any other value for seed sets the generator to a random starting point. rand retrieves the pseudorandom numbers that are generated. Calling rand before any call to srand generates the same sequence as calling srand with seed passed as 1.
看到英文就迷瞪…大概就是為srand函式需要一個隨機源來為rand函式設定亂數,那隨機源哪來的呢??時間時時刻刻在變,來呼叫電腦上的時間不就迎刃而解了嘛,
srand((unsigned) time(NULL));
第一次使用

第二次使用
到這里就解決了隨機的問題!
2、反復捉鱉與程式設計
一個程式,應有自己的界面,玩法,所以我們來將其優化一下,
先創建一個選單函式,
void menu()
{
printf("1.抽取————————0.放棄\n");
}
進入程式,選擇進行抽取還是放棄,
而這個程式有可能被重復使用,所以還得有個回圈,并且是那種先進入回圈后判斷條件的do while陳述句可以幫我們實作,
do
{
menu();
scanf("%d", &input);
}while(input);
下一步,我們要根據使用者的選擇去進行下一步,
if分支可以實作,但是用switch進行多分支回圈比if方便許多,
do
{
menu();
scanf("%d", &input);
switch (input)
{
case 1:
break;
case 0:
break;
}
} while (input);
當使用者選擇1后,程式要開始抽號輸出,我需要的是1-27號,所以用取模來實作
do
{
menu();
scanf("%d", &input);
Sleep(1000);
switch (input)
{
case 1:
printf("抽到的學號是:%d\n", rand() % 27 + 1);
break;
case 0:
break;
}
} while (input);
至此,游戲
3、細節優化
在使用中發現,當使用者選擇1后,發現程式運行的太快,所以需要程式運行慢一點,也給在等待的同學中一點緊張感,
Sleep函式(程式休眠函式)
int input = 0;
do
{
menu();
scanf("%d", &input);
switch (input)
{
case 1:
Sleep(1000);
printf("抽到的學號是:%d\n", rand() % 27 + 1);
break;
case 0:
break;
}
} while (input);
至此,一個完整的程式就出爐了!以后會經常寫一點實用的,希望大家多多關注!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/277424.html
標籤:其他
上一篇:DAY 1
下一篇:藍橋備戰準備記錄 1
