求助:各位大哥请帮我写一个产生随机数的函数,好吗?
请教:
是这样的,我需要生产 16 个随机数字
0,1,2,3,4,5,6,7,8,9,10,
11,12,13,14,15
他们这 15个数的顺序是随机的
把这 15 个随机数放到 myrand[16] 里
谢谢!
[解决办法]
#include<time.h>
#include<stdlib.h>
#include<stdio.h>
int myrand[16]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
void main()
{
int a;
srand((unsigned)time(NULL));
a = myrand[rand()%16];//确保a 在1--15
printf("%d\n",a);
}
[解决办法]
- C/C++ code
#include <stdio.h>#include <stdlib.h>#include <time.h>void GetRand(int s[], int size);void swap(int *a, int *b);void output(int s[], int size);int main(){ srand( (unsigned)time( NULL ) ); int s[]={0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; GetRand(s, 16); output(s, 16); return 0;}void GetRand(int s[], int size){ int i; for(i=0; i<size; i++) //打乱顺序,1次若不理想,可增加次数 { swap(&s[i], &s[rand()%size]); }}void swap(int *a, int *b){ int temp = *a; *a = *b; *b = temp;}void output(int s[], int size){ int i; for(i=0; i<size; i++) { printf("%d ", s[i]); } printf("\n\n");}
[解决办法]
自带的不好么?
[解决办法]
种子不同,产生的随机数就不同吗?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
是的。若种子相同,则会产生相同的随机数。rand()特意设计成这样,是为了方便程序的调试。
[解决办法]
你好像是想得到1-16的一个乱序排列? stl里面有现成的算法random_shuffle