1 / 10

Random Numbers

Random Numbers. Random Numbers. Call the random() method to generate a random double between 0 and 1. Need to import java.lang.Math in order to use it. double rNum; rNum = Math.random();. Random Numbers. A random number between 0 and 1 is not all that useful

rhonda
Télécharger la présentation

Random Numbers

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. Random Numbers

  2. Random Numbers • Call the random() method to generate a random double between 0 and 1. • Need to import java.lang.Math in order to use it. double rNum; rNum = Math.random();

  3. Random Numbers • A random number between 0 and 1 is not all that useful • We can manipulate the number however. • To generate a random integer in a range: (highNum – lowNum + 1) * Math.random() + lowNum • where highNum is the upper end of the range and lowNum is the lower end of the range

  4. You do • Write a program called RandomIntegers which will prompt the user for a high number and a low number and then output 5 random integers between the high and low numbers entered by the user.

  5. The Math Class • There are a number of useful math functions available in the Math class which is supplied with Java. • You need to include the java.lang.Math package to access them.

  6. The Math Class • Three useful functions are abs(), pow(), and sqrt(). • abs() returns the absolute value of an int or a double. • Its general form looks like this: abs(num)

  7. The Math Class • pow() returns the value of one number raised to the power of another. • Its general form looks like this: pow(double num1, double num2) • The general form tells you that there must be two numbers and that they must be separated by a comma and that they must both be doubles. • num1 is raised to the power of num2.

  8. The Math Class • sqrt()returns the square root of a number. • Its general form looks like this: sqrt(double num) • The general form tells you that there must be one number in the brackets and that it must be a double.

  9. The Math Class • To call any of these methods, you must include the class name: System.out.println(“The square root of 25 is: “ + Math.sqrt(25.0);

  10. You Do • P113: Review: PerfectSquare

More Related