1
float random_value(int min, int max)
{
        float temp = rand() / (float) RAND_MAX;
        return min + temp *(max - min);
}

我有这个功能,但它在 cooja 中不起作用,因为它总是一遍又一遍地输出相同的数字,而且我没有 time.h 库来制作srand(). 那么,我应该如何在 cooja 中打印不同的随机浮点值?我应该编写float random_value (float min, float max) 可用于实现虚拟温度传感器的 ac 函数,该传感器可配置为生成最小值和最大值之间的值。

4

2 回答 2

2

如果您无权访问time.h伪随机数生成器,另一种使用当前pid正在运行的进程的方法。

事实上,有时会以这种方式生成唯一的文件名:

getpid() returns the process ID (PID) of the calling process.
(This is often used by routines that generate unique temporary
filenames.)

这是一个打印电流pid并将其用作参数的小示例srand()

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
   int pid;
   pid = getpid();
   printf("Current process pid = %d\n", pid);
   srand((unsigned int)pid);
   printf("Random number: %d\n", rand()%100);
   return 0;
}

运行一次:

Current process pid = 197
Random number: 8

再次运行它:

Current process pid = 5612
Random number: 76 
于 2021-05-05T03:49:51.133 回答
0

如果您在 Linux 上运行,请阅读random(7)。您可以通过使用getrandom(2)系统调用或打开/dev/random设备来播种您的 PRNG(请参阅random(4)

于 2021-05-06T04:08:48.840 回答