Generating a random number within a range (both po

2019-08-31 08:38发布

问题:

Possible Duplicate:
Generating random number in a range with Java

I'm trying to create a single method to generate random numbers between two numbers, but I want it to work with any of these ranges (inclusive):

1 to 10
-5 to -10
-10 to 10

回答1:

Show you some code, it only demo the idea:

int myRand(int min, int max) {
    int r = rand();
    int range = max - min + 1;
    return r % range + min;
}


标签: java random