昨天面试,面试官问了我一题关于伪随机数的问题。问题大概如下: 通过编程方法实现5个伪随机数

而且这5个随机数的和为100。当时我想到了C语言中有可以生成随机数的函数,但是我不知道是什么了,面试结束后我查了一下,原来是srand() 、rand()函数。当初面试的人告诉我用random()函数,我回来是也试了试,但是总是报错“error C2065: 'random' : undeclared identifier”,在此请教高手求助,用random函数编写程序。我贴上用rand()函数实现的程序。
/********************************************************/
/*此代码生成5个100以内的伪随机数,5个随机数和为100*/
/*代码编写人:loveC2012*/
/*代码编写时间:2011/3/31 星期四*/
/********************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
srand((unsigned)time(NULL)); //播种子
int a=0,b=100,t=0;
a=rand()%90; //生成第一个随机数
t=t+a;
int c=b-a; //限制随机数的范围
printf("t=%d ",t);
printf("rand1:%2d\n",a);
for(int i=2;i<5;i++) //循环为了生成3个的随机数
{
a=rand()%c;
c=c-a;
t=t+a;
printf("t=%d ",t);
printf("rand%d:%2d\n",i,a);
}

a=100-t; //生成最后一个随机数
printf("t=100 ");
printf("rand5:%2d\n",a);

return 0;
}

我在网上查看过一些关于random函数的资料,random函数是跟randimze函数一起使用的。作用跟rand函数和srand函数一样。
我在linux下,把你的程序该了一下,运行是可以的。我猜random函数是Linux C下的函数,而不是标准C,所以运行会报错。
下面是修改后的程序:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
// int randomize(); //播种子
srand((unsigned)time(NULL));
int a=0,b=100,t=0,i=0;
a=random()%90; //生成第一个随机数
t=t+a;
int c=b-a; //限制随机数的范围
printf("t=%d ",t);
printf("random1:%2d\n",a);
for(i=2;i<5;i++) //循环为了生成3个的随机数
{
a=rand()%c;
c=c-a;
t=t+a;
printf("t=%d ",t);
printf("random%d:%2d\n",i,a);
}

a=100-t; //生成最后一个随机数
printf("t=100 ");
printf("random5:%2d\n",a);

return 0;
}
上面程序虽然能够执行,但是如果使用"int randomize(); "初始化的时候,运行结果都是一样的,也就是说没有达到真正上的随机。但是用"srand((unsigned)time(NULL));”,结果就是真正上的随机了。

回答如果可以给点分呗。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-03-31
看了一下代码,请问一下,你代码那里用到'random' 这个函数了追问

我这个代码没有用random函数,使用rand函数写的,我想请教如何用random函数编写。

相似回答