110 likes | 333 Vues
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
E N D
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 • 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
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.
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.
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)
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.
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.
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);
You Do • P113: Review: PerfectSquare