1 / 5

Introduction to Computer Programming Math Random

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()

norman
Download Presentation

Introduction to Computer Programming Math Random

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Computer ProgrammingMath 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 generateintdiceValue; // 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);

More Related