日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

自动生成100个数据 c语言,用C语言随机函数生成100个不大于100的数的具体算法怎么写?...

發(fā)布時(shí)間:2023/12/20 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 自动生成100个数据 c语言,用C语言随机函数生成100个不大于100的数的具体算法怎么写?... 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

http://blog.tianya.cn/blogger/post_show.asp?idWriter=0&Key=0&BlogID=382219&PostID=4547421

以上網(wǎng)有詳細(xì)的說(shuō)明

/*已經(jīng)上機(jī)通過(guò)測(cè)試:*/

#include

main()

{

int a[100],i; /*定義數(shù)組存放100個(gè)數(shù)*/

for(i=0;i<100;i++)

a[i]=random(100); /*產(chǎn)生100以內(nèi)的數(shù)*/

for(i=0;i<100;i++)

printf("%d ",a[i]); /*打印輸入*/

getch();

}

在C語(yǔ)言函數(shù)庫(kù)中包含了一個(gè)產(chǎn)生隨機(jī)數(shù)的函數(shù):

int rand( void );

在函數(shù)庫(kù)中對(duì)這個(gè)函數(shù)的說(shuō)明是:

The rand function returns a pseudorandom integer in the range

0 to RAND_MAX. Use the srand function to seed the pseudorandom

-number generator before calling rand.

而在C語(yǔ)言函數(shù)庫(kù)中是這樣定義RAND_MAX的:

/* Maximum value returned by "rand" function

*/

#define RAND_MAX 0x7FFF

所以,函數(shù)int rand( void );返回的是一個(gè)界于0~32767(0x7FFF)之

間的偽隨機(jī)數(shù),包括0和32767。注意,這里產(chǎn)生的是偽隨機(jī)數(shù),不是真正意

義上的隨機(jī)數(shù),看下面的程序:

#include "stdlib.h"

#include "stdio.h"

void main( void )

{

/* Display a number. */

printf( " %6d\n", rand() );

getchar();

}

程序運(yùn)行的結(jié)果是:

346

多次運(yùn)行這個(gè)程序,發(fā)現(xiàn)每次產(chǎn)生的結(jié)果都是346(不同的機(jī)器可能產(chǎn)生

的結(jié)果不一樣),這就是所謂的偽隨機(jī)數(shù)。偽隨機(jī)數(shù)是通過(guò)一個(gè)公式來(lái)運(yùn)算

出來(lái)的,所以,每次產(chǎn)生的偽隨機(jī)數(shù)都一樣。那么,如何才能產(chǎn)生真正意義

上的隨機(jī)數(shù)呢?這就有一個(gè)隨機(jī)種子的問(wèn)題。在C語(yǔ)言標(biāo)準(zhǔn)函數(shù)庫(kù)中,有這

么一個(gè)函數(shù):

void srand( unsigned int seed );

在《The c programming language》中對(duì)這個(gè)函數(shù)是這樣描述的:

srand uses seed(函數(shù)變量聲明中的seed) as the seed(隨機(jī)函數(shù)中種子

的意思) for a new sequence of pseudo-random numbers. The

initial seed is 1.

所以,要產(chǎn)生真正意義上的隨機(jī)數(shù),那么就要求每次提供的種子不一樣,一

般情況下,都設(shè)置時(shí)間為隨機(jī)函數(shù)的種子。看下面的一段程序:

/* RAND.C: This program seeds the random-number generator

* with the time, then displays 10 random integers.

*/

#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.

將當(dāng)前時(shí)間設(shè)置成隨機(jī)函數(shù)的種子,所以每次產(chǎn)生的數(shù)都不一樣

*/

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

每次運(yùn)行這個(gè)程序,產(chǎn)生的隨機(jī)數(shù)都不一樣,這樣就達(dá)到了隨機(jī)數(shù)的要求了

總結(jié)

以上是生活随笔為你收集整理的自动生成100个数据 c语言,用C语言随机函数生成100个不大于100的数的具体算法怎么写?...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。