亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

C/C++產(chǎn)生指定范圍和不定范圍隨機數(shù)的實例代碼

 更新時間:2013年11月20日 11:13:40   作者:  
C/C++產(chǎn)生隨機數(shù)用到兩個函數(shù)rand() 和 srand(),這里介紹不指定范圍產(chǎn)生隨機數(shù)和指定范圍產(chǎn)生隨機數(shù)的方法代碼大家參考使用

一. 不指定范圍產(chǎn)生隨機數(shù)
用到函數(shù)rand(),函數(shù)原型為int ra
nd(),無參數(shù)。此時會產(chǎn)生一個介于0~RAND_MAX間的整數(shù)。RAND_MAX的大小可以查看,在include文件夾(linux在usr目錄、windows在安裝目錄)的stdlib.h可以看到,linux下其值為2147483647(),其值與具體系統(tǒng)有關(guān)。
參考代碼:

復(fù)制代碼 代碼如下:

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

int main()
{
        int i;
        for(i=0; i<10; i++)  //隨機產(chǎn)生10個數(shù)。
        {
            printf("%d\n", rand());
        }
        return 0;
}

二. 指定范圍產(chǎn)生隨機數(shù),產(chǎn)生0到某個數(shù)的隨機數(shù)

沒有現(xiàn)成的函數(shù),但是可以通過取余得到

復(fù)制代碼 代碼如下:

#include<stdio.h>
#include<stdlib.h>
#define Random(x) (rand() % x) //通過取余取得指定范圍的隨機數(shù)
int main()
{
        int i;
        int dis;               //產(chǎn)生[0, dis)之間的隨機數(shù),注意不包括dis
        for(i=0; i<10; i++)
        {   
            printf("%d\n", Random(dis));
        }
        return 0;
}

說明下:假設(shè)dis取5

注意一個問題:以上兩個程序每次執(zhí)行產(chǎn)生的結(jié)果是相同的,既是個偽隨機數(shù)。rand()產(chǎn)生隨機數(shù)與具體的種子有關(guān),當(dāng)不特意用srand()獲取種子時,種子的默認值為1,因此需要用srand()函數(shù)產(chǎn)生不同的種子,srand函數(shù)原型:void srand(unsigned seed);為了產(chǎn)生不同的種子值,通常用時間作為參數(shù)值。例如對于一,修改程序如下:

復(fù)制代碼 代碼如下:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main()
{
        int i;
        srand((int)time(NULL));     //每次執(zhí)行種子不同,生成不同的隨機數(shù)
        for(i=0; i<10; i++)
        {
          printf("%d\n", rand());  //因為執(zhí)行太快,不到一秒鐘,10個隨機數(shù)是相通的,但是每次執(zhí)行是不同的
        }
        return 0;
}

三. 指定范圍產(chǎn)生隨機數(shù)

要求:指定范圍(m,n),m、n關(guān)系不定,隨機數(shù)包括m和n
想方設(shè)法,把范圍(m,n)改變到(0,X),到最后再轉(zhuǎn)移回去。三種情況

復(fù)制代碼 代碼如下:

1:m=n此時不該叫隨機數(shù),這里返回m
2:m>n:
        標(biāo)記pos=n,距離差pos=m-n+1
     返回 rand() % dis + pos

3:n>m:
        標(biāo)記pos=m,距離差=n-m+1
     返回rand()%dis + pos

參考代碼:

復(fù)制代碼 代碼如下:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int Random(int m, int n)
{
        int pos, dis;
        if(m == n)
        {
            return m;
        }
        else if(m > n)
        {
            pos = n;
            dis = m - n + 1;
            return rand() % dis + pos;
        }
        else
        {
            pos = m;
            dis = n - m + 1;
            return rand() % dis + pos;
        }
}
int main()
{
        int i, m, n;
        srand((int)time(NULL));
        m = -3;
        n = -7;
        for(i=0; i<10; i++)
        {
            printf("%d\n", Random(m, n));
        }
        return 0;
}

升華
srand((unsigned)time(null));
(a,b) (rand()%(b-a+1))+a-1
[a,b) (rand()%(b-a))+a
(a,b] (rand()%(b-a))+a+1
[a,b] (rand()%(b-a+1))+a

相關(guān)文章

最新評論