gpt4 book ai didi

c - 在 C 中无法理解此 PRNG 代码

转载 作者:太空宇宙 更新时间:2023-11-04 07:38:55 25 4
gpt4 key购买 nike

#include <stdio.h>


double seed=0.579832467;

main(ac, av)
int ac;
char *av[];
{
/* declare variables */
float *buf, fac;
int sf, ne, i;

/* prototypes? ( shouldn't they be outside the main ) */
double rnd(), sd;

/* gets the number of elements from command line */
ne = atoi(av[1]);

/* assigns the size of float ( in bytes ) to integer value */
sf = sizeof(float);

/* allocates appropriate memory for random number generation */
buf = (float *)malloc(ne*sf);

/* type cast, why?? */
sd = (double)(ne);

/* no idea what initrnd does */
initrnd(sd/(sd+187.9753));

/* checks if memory allocation is successful */
if (buf == NULL)
{
fprintf(stderr, "rndneg: can't allocate %d bytes for buffer\n", ne*sf);
exit(-1);
}

/* fills buffer with random number */
for (i=0; i<ne; i++)
{
buf[i] = (float)(rnd());
}

/* writes the buffer, how does it know the file name? */
write(1, buf, ne*sf);
}

/* random number generating function */
double rnd()
{
seed *= 997.0;
seed -= (double)((int)(seed));
return(seed);
}


initrnd(sd)

/* again no idea, why isn't this function void */
double sd;
{
seed = sd;
return(0);
}

这是 PRNG 的一些代码。我对 C 不是很有经验,这段代码中的一些东西对我来说完全没有意义。我试图对代码发表评论以跟踪发生了什么。如果能澄清一些我不明白的事情,我将不胜感激。特别是同名变量和函数的声明,以及 initrnd 子例程,似乎没有在程序或我在 Internet 上找到的任何库中定义。

非常感谢。

最佳答案

这看起来确实很古老。

对您的问题的一些回答:

  1. 不,原型(prototype)不需要是外部函数。这也许是最常见的,但不是必需的。
  2. initrnd()只需设置全局 seed变量为特定值,然后在 PRNG 中使用。
  3. 数据写入stdout ;假定使用文件描述符 1 .这种神奇常数的使用不是很漂亮,应该写成 stdout (来自 <stdio.h>)。

关于c - 在 C 中无法理解此 PRNG 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6048335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com