我已经为此挠头太久了。我看到了很多关于如何在 C 循环中处理随机生成的主题,但是当涉及两个循环时我什么也没看到。
下面是我的代码:
typedef struct
{
char qh_uid[6];
long int qh_vd;
long int qh_pd;
long int qh_id;
double qh_value;
}quote_history;
int records_size = 20;
int batch_size = 5;
char *rand_str(char *dst, int size)
{
static const char text[] = "abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int i, len = size;
for ( i = 0; i < len; ++i )
{
dst[i] = text[rand() % (sizeof text - 1)];
}
dst[i] = '\0';
return dst;
}
char *rand_tstp(char *dst, int size)
{
static const char text[] = "0123456789";
int i, len = size;
for ( i = 0; i < len; ++i )
{
dst[i] = text[rand() % (sizeof text - 1)];
}
dst[i] = '\0';
return dst;
}
double randfrom(double min, double max)
{
double range = (max - min);
double div = RAND_MAX / range;
return min + (rand() / div);
}
quote_history *feed_batch(quote_history *qh_batch, int batchsize)
{
int j;
char mytext[6];
char mylong[17];
for (j = 0; j < batchsize; ++j)
{
quote_history qh_aux;
printf("uid : %s - value : %lf\n",rand_str(mytext, sizeof mytext), randfrom(0,100000));
strcpy(qh_aux.qh_uid, rand_str(mytext, sizeof mytext));
qh_aux.qh_vd = strtol(rand_tstp(mylong, sizeof mylong), NULL, 10);
qh_aux.qh_pd = strtol(rand_tstp(mylong, sizeof mylong), NULL, 10);
qh_aux.qh_id = strtol(rand_tstp(mylong, sizeof mylong), NULL, 10);
qh_aux.qh_value = randfrom(0,100000);
qh_batch[j] = qh_aux;
}
printf("--------------\n");
return qh_batch;
}
int
main(int const argc,
const char ** const argv) {
quote_history *subArray;
srand(time(NULL));
int k;
for (k = 0; k < (int)(records_size/batch_size); ++k) {
subArray= (quote_history*)calloc(batch_size, sizeof(quote_history));
subArray = feed_batch(subArray, batch_size);
// Do something with subArray
free(subArray);
}
}
好吧,基本上,我想做的是生成 struct quote_history 的批次(作为数组),其中一些值是随机生成的,然后处理该批次并移至另一个批次。
出于某种原因,随机生成在 feed_batch 函数中运行良好,但是当它移动到循环中的下一个项目时,批次始终保持不变。
忘记粘贴代码的结果:
uid : qJfzrJ - value : 64938.995598
uid : LyCadK - value : 23030.096583
uid : dcOicU - value : 26016.211568
uid : BmpSTV - value : 76145.000279
uid : aQvABq - value : 92286.726130
--------------
uid : qJfzrJ - value : 64938.995598
uid : LyCadK - value : 23030.096583
uid : dcOicU - value : 26016.211568
uid : BmpSTV - value : 76145.000279
uid : aQvABq - value : 92286.726130
--------------
uid : qJfzrJ - value : 64938.995598
uid : LyCadK - value : 23030.096583
uid : dcOicU - value : 26016.211568
uid : BmpSTV - value : 76145.000279
uid : aQvABq - value : 92286.726130
--------------
uid : qJfzrJ - value : 64938.995598
uid : LyCadK - value : 23030.096583
uid : dcOicU - value : 26016.211568
uid : BmpSTV - value : 76145.000279
uid : aQvABq - value : 92286.726130
--------------
我尝试了许多组合(例如在循环中循环而不是 feed_batch 函数)但没有成功。
我希望有人能帮助我。
弗洛里安