1. Write a program to simulate a dice, and print out the minimum times to throw out all the numbers.
 
[1] 入門用法

srand( time(NULL) );
for( i = 0; i < 10; i++ )
    printf( "Random number #%d: %d\n", i, rand() );

取 1-10 的亂數 a=(rand() % 10) +1

取 1-100 的亂數 a=(rand() % 100) +1

取 100-1000 的亂數 a=(rand() % 901) +100

2. 亂數種子

 

將上述的程式多執行幾次會發現,怎麼每次亂數產生的都一樣?原因是沒設亂數種子。

那什麼叫亂數種子?

原理我不講了 < 因目的是要 "會" 用就好 >,簡單的說產生器是一組公式,公式要給「初始值」。

再怎麼給亂數這組公式一個初始值?用 srand( ) 。

那初始值該給多少?初始值給固定的值都沒用,要會隨著環境變動的值才有意義,

像是 記憶體使用量、process id 、CPU 使用率 等,這些都是會隨環境變動,

但有些變動性可能不大,而最常用來給初始值的,是時間,所以上述程式改如下。

 

 

 

#include<stdio.h>
#include<conio.h>
#include<time.h>
#include<stdlib.h>

int dice( )
{
int cnt = 0, a = 0, tem = 0;
int numTime[7] = { 0 } ;

srand( time(NULL) );
while( tem == 0 )
{
tem = 1;
a = rand()%6+1;
numTime[a]++;
cnt++;
for(int i=1; i<=6; i++)
tem = tem * numTime[i];
printf("Dice number %d times %d\n",a, cnt);
}
return cnt;
}


int main()
{
printf("%d \n",dice());

_getch();
return 0;
}

 

arrow
arrow
    全站熱搜

    大玩家闖天涯 發表在 痞客邦 留言(0) 人氣()