簡體   English   中英

如果我沒有 time.h 庫來執行 srand,如何在 cooja(c 代碼)中生成隨機浮點值

[英]How to generate a random float values in cooja (c code) if I don't have time.h library to perform srand

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

我有這個 function,但它在 cooja 中不起作用,因為它總是 output 一遍又一遍地使用相同的數字,而且我沒有 time.h 庫來制作srand() 那么,我應該如何在 cooja 中打印不同的隨機浮點值? 我應該寫一個 c function float random_value (float min, float max)可以用來實現虛擬溫度傳感器,可以配置為生成最小值和最大值之間的值。

如果您無權訪問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 

如果您在 Linux 上運行,請閱讀random(7) 您可以使用getrandom(2)系統調用或打開/dev/random設備來播種 PRNG(請參閱random(4)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM