rand函數(shù)也是調(diào)用dos的時(shí)鐘,進(jìn)行的偽隨機(jī)函數(shù).

創(chuàng)新互聯(lián)公司于2013年創(chuàng)立,先為云安等服務(wù)建站,云安等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為云安企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問(wèn)題。
你也可以使用時(shí)鐘來(lái)模擬隨機(jī)函數(shù).
可以試用gettime這個(gè)函數(shù):
long int MyRand(int x)
{
struct time t1,t2,t3;
gettime(t1);
int y1=t1.ti_hund;//取1/100s作為基數(shù)
gettime(t2);
int y2=t2.ti_hund;//取1/100s作為基數(shù)
gettime(t3);
int y3=t3.ti_hund;//取1/100s作為基數(shù)
return y1*y2*y3;//產(chǎn)生的隨機(jī)數(shù)0~99*99*99
}
源程序代碼以及算法解釋如下:
產(chǎn)生1-10隨機(jī)數(shù)程序:
#include iostream
#include time.h
using namespace std;
int main()
{
const int n = 10;//定義隨機(jī)數(shù)個(gè)數(shù)
int number[n] = { NULL };//定義隨機(jī)數(shù)存儲(chǔ)的數(shù)組
srand((unsigned)time(NULL));//初始化隨機(jī)函數(shù)
number[0] = rand() % n;//第一個(gè)隨機(jī)數(shù)無(wú)需比較
cout number[0] " ";
for (int i = 1; i n; i++)//其余隨機(jī)數(shù)循環(huán)產(chǎn)生
{
int j = 0;
number[i] = rand() % n;//產(chǎn)生隨機(jī)數(shù)
while (1)
{
if (number[i] == number[j])//若有相同則繼續(xù)循環(huán)重新安排隨機(jī)數(shù)
{
number[i] = rand() % n;//產(chǎn)生隨機(jī)數(shù)
j = 0;//若遇到相同的就從頭遍歷
continue;
}
if (j == (i - 1))//若遍歷完就跳出
break;
j++;
}
cout number[i] " ";
}
cout endl;
return 0;
}
程序運(yùn)行結(jié)果如下:
擴(kuò)展資料:
利用vector進(jìn)行隨機(jī)數(shù)輸出:
#include iostream
#include vector
#include time.h
using namespace std;
int main()
{
const int n = 10;
int randnum;
vectorint number;
for (int i = 0; i n; i++)
{
number.push_back(i + 1);????//從尾部添加元素
cout number[i] " ";
}
cout endl;
srand((unsigned)time(NULL));
for (int j = 0; j n; j++)?????//其余隨機(jī)數(shù)循環(huán)產(chǎn)生
{
randnum = rand() % (n - j);????//rand函數(shù)生成的隨機(jī)數(shù)是0-(n-1)
cout number.at(randnum) " ";
number.erase(number.begin() + randnum);
}
cout endl;
return 0;
}
一、首先包含必要的頭文件
#includestdio.h
這個(gè)包含用于輸入輸出的函數(shù)。
#includestdlib.h
這個(gè)包含初始化隨機(jī)數(shù)種子、產(chǎn)生隨機(jī)數(shù)的函數(shù)。
#includetime.h
這個(gè)包含與時(shí)間有關(guān)的函數(shù),初始化隨機(jī)數(shù)種子時(shí)可以用到。
二、使用如下公式產(chǎn)生在區(qū)間[min,max]之間的隨機(jī)數(shù)
int r=rand()%(max-min+1)+min;
三、一個(gè)例子,產(chǎn)生10個(gè)[1,100]的隨機(jī)整數(shù)
#include stdio.h
#include stdlib.h
#include time.h
int main()
{
const int min=1,max=100;
int i,r;
//用當(dāng)前時(shí)間初始化隨機(jī)數(shù)種子
srand(time(NULL));
printf("隨機(jī)產(chǎn)生的10個(gè)1-100的整數(shù)是:");
for(i=0;i10;i++)
{
r=rand()%(max-min+1)+min;
printf("%d,",r);
}
return 0;
}
四、運(yùn)行結(jié)果的截圖
截圖1
截圖2
網(wǎng)站標(biāo)題:c語(yǔ)言中隨機(jī)函數(shù)的寫(xiě)法 c語(yǔ)言中,產(chǎn)生隨機(jī)數(shù)的函數(shù)及其應(yīng)用代碼舉例
當(dāng)前URL:http://www.chinadenli.net/article48/ddoipep.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供軟件開(kāi)發(fā)、品牌網(wǎng)站制作、品牌網(wǎng)站設(shè)計(jì)、品牌網(wǎng)站建設(shè)、移動(dòng)網(wǎng)站建設(shè)、面包屑導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)