用 C 語言 程式設計 產生 M序列!
- 2022-10-27
你是說要產生隨機序列嗎?
#include
#include
#include
main()
{int i;
int[M];(m的值自己定)
for(i=0;i srand( (unsigned)time( NULL ) ); int[i]=rand(); } 以上這個函式可以實現了 這裡給你擴充套件學習下 用random也可以產生 還告訴你srand( (unsigned)time( NULL ) ); 是幹什麼用的。 #include main() { int a[100],i; /*定義陣列存放100個數*/ for(i=0;i<100;i++) a[i]=random(100); /*產生100以內的數*/ for(i=0;i<100;i++) printf(“%d ”,a[i]); /*列印輸入*/ getch(); } 在C語言函式庫中包含了一個產生隨機數的函式: int rand( void ); 函式int rand( void );返回的是一個界於0~32767(0x7FFF)之 間的偽隨機數,包括0和32767。注意,這裡產生的是偽隨機數,不是真正意 義上的隨機數,看下面的程式: #include “stdlib。h” #include “stdio。h” void main( void ) { /* Display a number。 */ printf( “ %6d\n”, rand() ); getchar(); } 程式執行的結果是: 346 多次執行這個程式,發現每次產生的結果都是346(不同的機器可能產生 的結果不一樣),這就是所謂的偽隨機數。偽隨機數是透過一個公式來運算 出來的,所以,每次產生的偽隨機數都一樣。那麼,如何才能產生真正意義 上的隨機數呢?這就有一個隨機種子的問題。在C語言標準函式庫中,有這 麼一個函式: void srand( unsigned int seed ); 要產生真正意義上的隨機數,那麼就要求每次提供的種子不一樣,一 般情況下,都設定時間為隨機函式的種子。看下面的一段程式: #include “stdlib。h” #include “stdio。h” #include “time。h” void main( void ) { int i; /* Seed the random-number generator with current time so that the numbers will be different every time we run。 將當前時間設定成隨機函式的種子,所以每次產生的數都不一樣 */ srand( (unsigned)time( NULL ) ); /* Display 10 numbers。 */ for( i = 0; i < 10;i++ ) printf( “ %6d\n”, rand() ); } Output 6929 8026 21987 30734 20587 6699 22034 25051 7988 10104 每次執行這個程式,產生的隨機數都不一樣,這樣就達到了隨機數的要求了