c++ - 如何生成范围内的随机数 (-x,x)

标签 c++ random

嗨 可以使用 rand() 在 (-x,x) 范围内生成随机数吗?如果不是,我如何生成该范围内的随机数?

最佳答案

// return a random number between 0 and limit inclusive.
int rand_lim(int limit) {

    int divisor = RAND_MAX/(limit+1);
    int retval;

    do { 
        retval = rand() / divisor;
    } while (retval > limit);

    return retval;
}

// Return a random number between lower and upper inclusive.
int rand_lim(int lower, int upper) {
    int range = abs(upper-lower);

    return rand_lim(range) + lower;
}

像往常一样,我在这个帖子中看到的所有其他人都可以/将会产生至少略有偏差的结果。

关于c++ - 如何生成范围内的随机数 (-x,x),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5129093/

相关文章:

c++ 模板参数列表中参数 1 的类型/值不匹配

c++ - 文件夹大小 linux

php - php中的测试数据

python - 洗牌一小组项目

python - 使用 randint 意外执行更新字典

c++ - 类模板 "std::iterator"的参数列表丢失

c++ - 从文件读取时获取垃圾字符

python - 如何使用 boost 元组返回两个 vector

random - 如何在DrScheme R5RS中使用 "random"函数

javascript - 为什么 Google Chrome 浏览器的 Math.random 数字生成器不是 *that* 随机数?