求编程序

来源:百度知道 编辑:UC知道 时间:2024/05/09 04:30:49
1) Using rand() to write a function rand5() that produces a random integer between the numbers 1 and 5, that is, to produce a number from the set {1, 2, 3, 4, 5} with equal probability.
(2) Using rand5() only to write a function rand7() that produces a random integer between the numbers 1 and 7, that is, to produce a number from the set {1, 2, 3, 4, 5, 6, 7} with equal probability.
(3) Test rand7() 1,000,000 times to verify that each number in the set {1, 2, 3, 4, 5, 6, 7} indeed is produced with about equal frequency.
c语言 这是三个程序

#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int rand5(void)
{
int num;
srand((unsigned)time(NULL));
num=rand()%5+1;
return num;
}
int rand7(void)
{
int num;
srand((unsigned)time(NULL));
num=rand()%7+1;
return num;
}
int main()
{
int num1,num2;
num1=rand5();
num2=rand7();
printf("rand5()=%d,rand7()=%d\n",num1,num2);
return 0;
}

the third question:
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int rand7(void)
{
int num;
srand((unsigned)time(NULL));
num=rand()%7+1;
return num;
}
int main()
{
long i;
int a[7]={0}; //save the times that every number apears
for (i=0;i<1000000;i++)a[rand7()-1]++;
for(i=0;i<7;i++)printf("%d:[%d]\n",i+1,a[i]);
return 0;
}