为什么这个函数不会生成随机数?

时间:2014-09-23 07:51:01

标签: c++ random zeromq

#include <memory>
#include <functional>

#include <zmq.hpp>
#include <zhelpers.hpp>   

 void main(){
    char identity[10] = {};
    sprintf(identity, "%04X-%04X", within(0x10000), within(0x10000));
    printf("%s\n", identity);
}

我从这里参考: https://github.com/imatix/zguide/blob/master/examples/C%2B%2B/asyncsrv.cpp

2 个答案:

答案 0 :(得分:1)

我不知道within()的作用,但您可能希望使用新方法生成随C++11引入的随机数。该链接有一个很好的例子。

如果链接在将来的某个时间内无效,请参阅以下相关代码:

#include <iostream>
#include <random>
int main {
    // Seed with a real random value, if available
    std::random_device rd;

    // Choose a random number between 1 and 6
    std::default_random_engine engine(rd());
    std::uniform_int_distribution<int> uniform_dist(1, 6);
    int randomNumber = uniform_dist(engine);
    int anotherRandomNumber = uniform_dist(engine);
    std::cout << "Randomly-chosen number: " << randomNumber << '\n';
    std::cout << "Another Randomly-chosen number: " << anotherRandomNumber << '\n';
}

答案 1 :(得分:1)

虽然我对回答这么糟糕的问题犹豫不决......

根据Mike Seymour找到的within()的定义,您的代码相当于:

#include <stdlib.h>
#include <stdio.h>

#define within(num) (int) ((float) (num) * rand () / (RAND_MAX + 1.0))

void main(){
    char identity[10] = {};
    sprintf(identity, "%04X-%04X", within(0x10000), within(0x10000));
    printf("%s\n", identity);
}

此代码 生成(伪)随机数。您可能感到困惑的是,它确实在每次运行程序时生成相同的(伪)随机数。然而,这就是伪随机数生成器:给定相同的种子(因为您不通过srand()为种子生成种子),它们会生成相同的数字序列。 (因此“伪”。)

我强烈推荐其他阅读,例如man rand

相关问题