简体   繁体   中英

How do I generate random numbers within a range

computerTotal = (int) Math.ceil(Math.random() * 21);

Can someone show me how to get 16 - 21 random number I keep getting errors when i try to implement the Math.floor function... As you can see i'm not very good at putting functions within functions.

Many Thanks!

If Java, use the Random Class.

Random r = new Random();
int myRand = 16+ r.nextInt(6); //16+[0-6) = 16-21

For creating random numbers between (including) min and max , you can do this:

Math.floor(Math.random() * (max - min + 1)) + min

Edit: The JAVA tag was added only after I suggested this; before it had no tags hinting at a specific language at all – so that there might be better/already implemented methods for this in language X is well possible. This is a very generic approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM