使用模板怎么建站怎么做百度推廣
c 語言, 隨機(jī)數(shù),一個不像隨機(jī)數(shù)的隨機(jī)數(shù)
使用兩種方式獲取隨機(jī)數(shù),總感覺使用比例的那個不太像隨機(jī)數(shù)。
- 方法一:
rand()
獲取一個隨機(jī)數(shù),計(jì)算這個隨機(jī)數(shù)跟最大可能值RAND_MAX
(定義在stdlib.h
中)的比例數(shù)值,再用需要的范圍 100 跟這個相乘,得到一個隨機(jī)數(shù); - 方法二:直接用
rand() % 100
取余。
下面是兩種方法獲取到的 100 個數(shù)值:
#include "stdio.h"
#include "stdlib.h"
#include "time.h"int get_random_within(double max){float ratio = rand()/(double)RAND_MAX;return (int)(max * ratio);
}int main(){time_t t;srand(time(&t));printf("time is %lu", t);printf("\n\nuse random ratio to RAND_MAX to get random values: \n");for (int i=0;i<100; i++){if (i> 0 && i % 10 == 0){printf("\n");}int temp = get_random_within(100);if (temp < 10){printf(" %d ", temp);} else {printf("%d ", temp);}}printf("\n\nuse %% to get random values: \n");for (int i=0;i<100; i++){if (i > 0 && i % 10 == 0){printf("\n");}int temp = rand() % 100;if (temp < 10){printf(" %d ", temp);} else {printf("%d ", temp);}}printf("\n");return(0);
}