Download presentation
Presentation is loading. Please wait.
Published byPierce Hampton Modified over 8 years ago
1
Introduction to Computer Programming Math Random Dice
2
Random Number Math class – knows PI, E, how to give a random # and how to do many math functions Method random – knows how to pick a random number between 0 and 1. double randBase = Math.random() Now randBase is a double between 0 and 1, (ex:.051) but I want a dice value between 1 and 6 What can I do to randBase to get a dice value?
3
Random – Dice Multiply by 6. –Any fraction * 6 will not equal 6 or more. –Ex:.051 * 6 = 3.06 Chop off the remainder –Ex: 3 –Now I have a number between 0 and 5 Add 1 to the number –Ex: 4
4
Random –Code To get dice: double randBox = Math.random(); int dieVal = (int) ( randBox * 6) + 1; How to get cards (13)?
5
Random – Code Alternate Will this work: double x; // holds the random number we will generate int diceValue; // holds the value of the dice that we calculate from the random x = Math.random(); // generates a number between 0 and 1 x = x *6; // multiplies that number times 6 so the number will be from 0 to 5 diceValue = (int) x; // convert it to integer to chop off the decimal portion diceValue = diceValue +1; // with dice, we want 1-6, not 0-5, so we add 1 System.out.println ("The value of this die is " + diceValue);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.