C的隨機函式,如何直接產生公升序排列的30 100的整數n個?

時間 2021-06-18 23:24:38

1樓:官渡三哥

兩個知識點:

生成 [x, y] 間的 n 個隨機數;

如何實現公升序?

程式設計:

擴充套件一下,從命令列輸入 n, x, y, 適當檢查輸入合法性;

生成 [x, y] 間的 n 個隨機數,存入陣列;

對陣列公升序排序(這裡採用插入排序),輸出陣列。

Talk is cheap, show you the code

/*File: c_rand.c - Generate n random numbers in [x, y]

*/#include

#include

// for srand()

#include

// for time()

#include

// for isdigit()

#include

// for bool type in C

intN,X

,Y;// Number of randoms; range for random numbers [x, y]

int*a;

// Array to store the sorted numbers

/** The Insertion Sort method.

*/void

insertionSort

(int

*arr

,int

length)}

}/** Test if it's an integer input

*/bool

isInteger

(const

char*s

)return

isValidInteger;}

/** Generate random number in rang [x, y]

*/int

GenRndNum

(intx,

inty)/*

* Build n randoms in [x, y]

*/void

BuildRandoms

(intn,

intx

,inty)

}/** Print the sorted array of randoms

*/void

printArray

(int

*arr

,intn)

printf("

\n");}

intmain

(int

argc

,char

const

*argv

)/* Input validations */if(

isInteger

(argv[1

])&&

isInteger

(argv[2

])&&

isInteger

(argv[3

]))else

/* Build N numbers of randoms in [X, Y] */

BuildRandoms(N

,X,Y

);/* Sort the randoms in ascending order */

insertionSort(a

,N);/* Print the sorted array */

printArray(a

,N);/* Free array */

free(a

);return0;

}執行$ gcc -o c_rand c_rand.c

$ ./c_rand

Usage: c_rand n x y //n: number of randoms, x and y is the rang.

$ ./c_rand 5 30 100

Generating 5 random numbers between [30, 100] in ascending order ...

40 52 58 63 87

$./c_rand 15 30 100

Generating 15 random numbers between [30, 100] in ascending order ...

44 45 46 49 51 54 60 61 61 69 69 70 72 75 79

2樓:

rand 函式生成的數是利用演算法(例如,線性同餘)生成的假隨機數,並不能做到真隨機。因此,如果要產生某一範圍的數,直接用 rand 的返回值對區間終值取模,再加上區間起始值(例如,int val = rand ()%100 +30;),這樣產生的數列肯定不是有序的,那麼我們可以每產生乙個數,遍歷當前數列,選擇插入位置,然後執行n次之後就得到了乙個公升序排列、長度為n、範圍在[30,100]的數列,這樣看的話,最適合的資料結構應該是鍊錶(其實c++ stl 的 set更合適,不過你應該不會用)。

如何產生正態分佈的隨機數?

陳昊 老生常談的 Box Muller 方法不過實現有些不同,不用三角函式。參考 Generating Gaussian Random Numbers return a random double between zero and 1 inline double RandFloat returns ...

二元連續型隨機變數函式的概率密度有無直接的公式可以計算?

設座標變換 如果是單射,我們有公式 對稱的,需要求哪個把另外一邊代進去就行,最後統一換元就好。而對面積微元的處理參考積分換元就行。不需要非要把uv換成xy。例 設二元標準正態分佈 求出在座標變換 下 的密度函式。解 注意到這個變換除去乙個點後是1 1的,所以我們有 由微積分知識我們有 代入兩邊約掉 ...

在C 中如何實現復合多個函式的高階函式

guohc FuncCombinator的引數不固定所以只能傳入delegate的陣列。static void Main string args static Func FuncCombinator Delegate da TResult result TResult param return re...