关于随机数的一道编程

来源:百度知道 编辑:UC知道 时间:2024/05/27 08:24:59
(1) Use rand() to write a function rand3() that can produce a random integer between 1 and 3, that is, to produce a number from the set {1, 2, 3} with equal probability.
(2) Assume you ONLY have function rand3() from previous exercise, please write a function rand5() that can produce a random integer between 1 and 5, that is, to produce a number from the set {1, 2, 3, 4, 5} with equal probability.
(3) Test rand5() 1,000,000 times to verify that each number in the set {1, 2, 3, 4, 5} indeed is produced with about equal frequency.

第二问应该怎么做啊?
拜托讲得详细一点,偶是初学者。。luxiao6666的答案看了还是不会啊、、能不能把代码写出来。。

//---------------------------------------------------------------------------

#include <stdio.h>

#include <stdlib.h>
#define SR1 3
#define SR2 6
int rand3(void)
{
static int sd=0;
int *a;
if (!sd) {
a=malloc(sizeof(int)*100);
srand((unsigned int)a);
++sd;
free(a);
}

return rand()%SR1+1;
}
int rand5()
{

return (rand3()+rand3()+rand3()+rand3()+rand3())%SR2;

}
int main(int argc, char* argv[])
{
int r,i,a[5]={0};

for (i = 0; i<1000; i++) {
r=rand5();
++a[r-1];
printf("%d\t",r);
}
for (i = 0; i<SR2-1; i++) {
printf("%d:%d\n",i+1,a[i]);
}
return 0;
}
//---------------------------------------------------------------------------

int rand3(){
return rand()%3+1;
}
int rand5(){