introduction to computer programming math random

5
Introduction to Computer Programming Math Random Dice

Upload: norman

Post on 05-Jan-2016

20 views

Category:

Documents


2 download

DESCRIPTION

Introduction to Computer Programming Math Random. Dice. 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() - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Introduction to Computer Programming Math Random

Introduction to Computer ProgrammingMath Random

Dice

Page 2: Introduction to Computer Programming Math Random

Random NumberMath 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?

Page 3: Introduction to Computer Programming Math Random

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

Page 4: Introduction to Computer Programming Math Random

Random –Code

To get dice:

double randBox = Math.random();

int dieVal = (int) ( randBox * 6) + 1;

How to get cards (13)?

Page 5: Introduction to Computer Programming Math Random

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 randomx = Math.random(); // generates a number between 0 and 1x = x *6; // multiplies that number times 6 so the number will be from 0 to 5diceValue = (int) x; // convert it to integer to chop off the decimal portiondiceValue = diceValue +1; // with dice, we want 1-6, not 0-5, so we add 1System.out.println ("The value of this die is " + diceValue);