如何在范围内生成随机数(-x,x)

时间:2011-02-26 19:04:42

标签: c++ random

您好 可以使用rand()生成一个范围(-x,x)内的随机数。如果没有,我如何生成具有该范围的随机数?

3 个答案:

答案 0 :(得分:5)

// 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;
}

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

答案 1 :(得分:1)

我只是一个简单的基础程序员,但我觉得我错过了这一点。答案似乎很简单。请原谅VB代码

    Dim prng As New Random
    Const numEach As Integer = 100000
    Const x As Integer = 3 'generate random number within a range (-x,x) inclusive

    Dim lngth As Integer = Math.Abs(-x - x) + 1
    Dim foo(lngth - 1) As Integer 'accumualte hits here

    For z As Integer = 1 To (numEach * lngth)
        Dim n As Integer = prng.Next(lngth) 'generate number in inclusive range
        foo(n) += 1 'count it
        'n = x - n 'actual n
    Next

    Debug.WriteLine("Results")
    For z As Integer = 0 To foo.Length - 1
        Debug.WriteLine((z - x).ToString & " " & foo(z).ToString & " " & (foo(z) / numEach).ToString("n3"))
    Next
    Debug.WriteLine("")

典型结果

Results
-3 99481 0.995
-2 100214 1.002
-1 100013 1.000
0 100361 1.004
1 99949 0.999
2 99755 0.998
3 100227 1.002


Results
-3 100153 1.002
-2 99917 0.999
-1 99487 0.995
0 100383 1.004
1 100177 1.002
2 99808 0.998
3 100075 1.001

答案 2 :(得分:-1)

查看this question的答案。