游戲玩法:
電腦隨機生成一個亂數(1-100之間),玩家根據提示進行猜測,直到猜對為止,
相關知識點:
分支與回圈,亂數的生成,時間戳,標準輸入輸出,強制型別轉換等
時間戳和亂數的生成將在本篇blog中重點講解,其他知識點在其他blog中有重點講解,
代碼如下:
#include <stdio.h>
#include<stdlib.h>
#include<time.h>
void menu()
{
printf("################\n");
printf("#### 1.play ####\n");
printf("#### 0.exit ####\n");
printf("################\n");
}
void game()
{
int ret = rand();
int guess = 0;
ret = ret % 100 + 1;
while(1)
{
printf("Guess the number:>\n");
scanf("%d",&guess);
if(guess < ret)
{
printf("Your guess is smaller than the number\n");
}
else if(guess > ret)
{
printf("Your guess is bigger than the number\n");
}
else
{
printf("Congratulations, you guessed it\n");
break;
}
}
}
int main(){
int input = 0;
srand((unsigned int)time(NULL));
do
{
menu();
printf("make your choice:>");
scanf("%d",&input);
switch(input)
{
case 1:
game();
break;
case 0 :
printf("Exit the game\n");
break;
default:
printf("Wrong selection\n");
break;
}
}while(input);
return 0;
}
值得注意的是,該程式設計中使用了rand()和srand()這兩個函式,如果只單用rand這一個函式來生成亂數的話,生成的數字是偽亂數(每一次程式重新啟動時都生成相同的亂數),因此需要搭配srand這個函式進行使用,
srand是亂數發生器的初始化函式,當srand()中的數字不一樣時,rand函式每一次運行將生成不一樣的亂數,而要想每一次運行程式時srand()中的數字不一樣,將用到下面這個概念
時間戳
時間戳是將程式運行時的時間與計算機發明時間的差值,單位是秒
也就是說,隨著時間的流逝,每過一秒鐘,時間戳就加一,因此我們可以將時間戳放到srand()中,使得每一次運行程式,都可以重新初始化rand函式,保證每一次運行時所生成的數字不同,

而如果需要獲取當前程式運行時的時間戳,需要我們使用time()函式
time()函式

time_t是一種型別,當我們查看其背后源代碼時,可以發現他是long型別,也就是說是一個整數,剛好可以放到srand函式中,我們并不需要一個指標來存盤seconds的值,因此在這里寫NULL即可,而我們srand函式中需要一個unsigned int的值,因此前面添加強制型別轉換,我們這三個函式在使用的程序中,需要添加stdlib.h和time.h這兩個頭檔案
如果覺得這里的原理過于復雜,可以死記硬背生成亂數的這兩行代碼,
srand((unsigned int)time(NULL));
int ret = rand();
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/413635.html
標籤:其他
上一篇:C語言編-------------簡單猜數字游戲實作
下一篇:C語言小專案之猜數字
