頭文件為#include<stdlib.h>
定義函數(shù) :int rand(void)
rand()功能
產(chǎn)生隨機(jī)數(shù)
rand()會返回一隨機(jī)數(shù)值屿附,范圍在0至RAND_MAX 間
用"int x = rand() % 100;"來生成 0 到 100 之間的隨機(jī)數(shù)是一種方法碗殷,比較好的做法是: j=(int)(n*rand()/(RAND_MAX+1.0))產(chǎn)生一個0到n之間的隨機(jī)數(shù)。
srand()
函數(shù)定義:void srand(unsigned int seed)
函數(shù)功能:設(shè)置隨機(jī)數(shù)種子
函數(shù)說明:通乘罨簦可以用getpid()(獲取當(dāng)前進(jìn)程的進(jìn)程識別碼)或者time(NULL)(獲取當(dāng)前系統(tǒng)的時間信息)來充當(dāng)種子杏头,保持每次運(yùn)行時種子是不一樣的。
下面是用srand()和rand()制作的一款小游戲:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int main(){
int count = 3; //記錄每次生成多少個隨機(jī)數(shù)
while(1){
unsigned int seed = time(NULL); //1000
//設(shè)置隨機(jī)數(shù)的種子
srand(seed);
for(int i = 0; i < count; i++){
//生成一個隨機(jī)數(shù)
int temp2 = rand() % 9 + 1;
printf("%d ",temp2);
}
printf("\n");
// 延時2s
Sleep(2000);
//for(int i = 0; i < 10000000000/15*2; i++);
//刷新屏幕
system("cls");
/* mac
for(int i = 0; i < 20; i++){
printf("\n");
}
*/
int temp;
printf("請輸入:");
//重新設(shè)種子和之前生成時的種子一樣
srand(seed);
//接收用戶輸入 一個一個接收
// 1 2 3
// 1 2 4
for(int i = 0; i < count; i++){
scanf("%d", &temp);
//獲取對應(yīng)的生成的隨機(jī)數(shù)
int old = rand() % 9 + 1;
//比較輸入的和隨機(jī)數(shù)是否相同
//printf("old:%d\n", old);
if (temp != old){
printf("錯誤 退出沸呐!\n");
exit(EXIT_SUCCESS);
}
}
count++;
system("cls");
}
return 0;
}