C语言中随机数生成问题,急!

来源:百度知道 编辑:UC知道 时间:2024/06/03 16:23:33
#include<stdio.h>
#include<malloc.h>
#include<time.h>
#include<stdlib.h>

#define NULL 0
#define N 10

struct ch
{
char cha;
struct ch*next;
}*head=NULL,*p;

void main()
{

int len,i,j,c;
for(j=0;j<N;j++)
{
srand( (unsigned)time( NULL ));
len=1+rand()%16;
for(i=0;i<len;++i)
{
if(head==NULL)
{
head=(struct ch*)malloc(sizeof(struct ch));
c=65+rand()%26;
head->cha=c;
head->next=NULL;
p=head;
}
else
{
p->next=(struct ch*)malloc(sizeof(struct ch));
p=p->next;
c=65+rand()%26;
p->cha=c;
p->next=NULL;
}
}
for(p=head;p!=NULL;p=p->next)
printf("%c",p->cha);<

把srand( (unsigned)time(NULL)); 放在循环外面就好了,一次就行了,下面测试过了
#include<stdio.h>
#include<malloc.h>
#include<time.h>
#include<stdlib.h>

#define NULL 0
#define N 10

struct ch
{
char cha;
struct ch*next;
}*head=NULL,*p;

void main()
{

int len,i,j,c;
srand( (unsigned)time(NULL));
for(j=0;j<N;j++)
{

len=1+rand()%16;
for(i=0;i<len;++i)
{
if(head==NULL)
{
head=(struct ch*)malloc(sizeof(struct ch));
c=65+rand()%26;
head->cha=c;
head->next=NULL;
p=head;
}
else
{
p->next=(struct ch*)malloc(sizeof(struct ch));
p=p->next;
c=65+rand()%26;
p->cha=c;
p->next=NULL;
}
}
for(p=head;p!=NULL;p=p->next)
printf("%c",p->cha);
printf("\n");
free(head);
head=NULL;