1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <time.h> 4 5 /******************************************************************************* 6 Function: void randnum(int a, int b, unsigned int arr[], int n) 7 Description:产生n个a到b之间的随机数,放入数组arr中。 8 Calls: srand,rand,time 9 Called By:main 10 Input: 11 a,b:随机数的范围a=<随机数<b 12 n:数组的大小 13 Output: 14 arr:存放随机数的数组 15 Others: 产生的随机数为无符号整形数 16 *******************************************************************************/ 17 void randnum(int a, int b, unsigned int arr[], int n) 18 { 19 int i = 0; 20 srand((unsigned int)time(NULL)); 21 for (i = 0; i < n; i++) 22 { 23 arr[i] = rand()%(b - a) + a; 24 } 25 26 } 27 int main() 28 { 29 int i; 30 unsigned int a[20]; 31 randnum(100, 200, a, 20); 32 for (i = 0; i < 20; i++) 33 { 34 printf("a[%d] = %d\n", i, a[i]); 35 } 36 printf("\n"); 37 return 0; 38 }
结果:
1 a[0] = 102 2 a[1] = 112 3 a[2] = 196 4 a[3] = 181 5 a[4] = 175 6 a[5] = 193 7 a[6] = 127 8 a[7] = 120 9 a[8] = 192 10 a[9] = 173 11 a[10] = 100 12 a[11] = 166 13 a[12] = 168 14 a[13] = 189 15 a[14] = 124 16 a[15] = 168 17 a[16] = 169 18 a[17] = 130 19 a[18] = 109 20 a[19] = 171 21 22 请按任意键继续. . .