有趣的種子亂數

基本概念就是在我們利用配合函式來製造一個亂數,
首先在主程式先利用time給要呼叫的函式srand一個亂數,由此函式給予全域變數一個隨機數值,在回到主程式後進入迴圈,而迴圈列印中呼叫函式rand,函式rand進行運算後回傳數值給主程式列印。
範例如下:
#include<stdio.h>
#include<time.h>
static unsigned next =1;

int rand(void){
next = next *1031354217+15315;
return next / 65432%26163;
}
void srand(unsigned int seed){
next = seed;
}
int main(){
srand(time(0));
for(int i=1;i<=5;++i){
printf("%d\n",rand());
}

留言