我试图确定为什么将随机值写入数组会导致问题。
我实际上要求 rand()
生成 1 到 10 之间的数字(rand() %10 +1
之前srand(time(NULL))
),第一个值总是高于 10:它也是一个随机的,介于 10 到 20 之间。我真的不知道如何解决这个问题,因为它看起来像rand
andsrand
函数的问题。尽管如此,这是我的代码:
编辑:正确的代码,现在
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZEA 100
#define SIZEFREQ 10
int main()
{
int a[SIZEA]={0},frequency[SIZEFREQ]={0};
int i,temp,gothrough;
srand(time(NULL));
for(i=0;i<=SIZEA-1;i++)
{
a[i]=rand() %10 +1;
++frequency[a[i]-1];
}
printf("These are the elements in the vector:\n");
for(i=0;i<=SIZEA-1;i++)
{
printf("%3d,",a[i]);
}
printf("\nLet's try to put them in order\n");
for(gothrough=0;gothrough<=SIZEA-1;gothrough++)
{
for(i=0;i<=SIZEA-2;i++)
{
if (a[i]>a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}
for(i=0;i<=SIZEA-1;i++)
{
printf("%3d,",a[i]);
}
printf("\n\nValue Frequency\n");
for(i=0;i<=SIZEFREQ-1;i++)
{
printf("%5d%10d\n",i+1,frequency[i]);
}
return 0;
}`