Generating random integer from a range

前端 未结 13 1516
失恋的感觉
失恋的感觉 2020-11-22 03:12

I need a function which would generate a random integer in given range (including border values). I don\'t unreasonable quality/randomness requirements, I have four requirem

13条回答
  •  遇见更好的自我
    2020-11-22 03:38

    assume min and max are int values, [ and ] means include this value, ( and ) means not include this value, using above to get the right value using c++ rand()

    reference: for ()[] define, visit:

    https://en.wikipedia.org/wiki/Interval_(mathematics)

    for rand and srand function or RAND_MAX define, visit:

    http://en.cppreference.com/w/cpp/numeric/random/rand

    [min, max]

    int randNum = rand() % (max - min + 1) + min
    

    (min, max]

    int randNum = rand() % (max - min) + min + 1
    

    [min, max)

    int randNum = rand() % (max - min) + min
    

    (min, max)

    int randNum = rand() % (max - min - 1) + min + 1
    

提交回复
热议问题