Java Math naključno ()

Metoda Java Math random () vrne vrednost, ki je večja ali enaka 0,0 in manjša od 1,0.

Sintaksa random()metode je:

 Math.random()

Opomba : random()Metoda je statična metoda. Zato lahko metodo pokličemo neposredno z imenom razreda Math.

naključni () parametri

Math.random()Metoda ne sprejme nobenih parametrov.

random () Vrnjene vrednosti

  • vrne psevdonaključno vrednost med 0,0 in 1,0

Opomba : Vrnjene vrednosti niso resnično naključne. Namesto tega vrednosti generira določen računski postopek, ki izpolnjuje določen pogoj naključnosti. Zato se imenujejo psevdonaključne vrednosti.

Primer 1: Java Math.random ()

 class Main ( public static void main(String() args) ( // Math.random() // first random value System.out.println(Math.random()); // 0.45950063688194265 // second random value System.out.println(Math.random()); // 0.3388581014886102 // third random value System.out.println(Math.random()); // 0.8002849308960158 ) )

V zgornjem primeru lahko vidimo, da metoda random () vrne tri različne vrednosti.

Primer 2: Ustvari naključno število med 10 in 20

 class Main ( public static void main(String() args) ( int upperBound = 20; int lowerBound = 10; // upperBound 20 will also be included int range = (upperBound - lowerBound) + 1; System.out.println("Random Numbers between 10 and 20:"); for (int i = 0; i < 10; i ++) ( // generate random number // (int) convert double value to int // Math.round() generate value between 0.0 and 1.0 int random = (int)(Math.random() * range) + lowerBound; System.out.print(random + ", "); ) ) )

Izhod

 Naključne številke med 10 in 20: 15, 13, 11, 17, 20, 11, 17, 20, 14, 14,

Primer 3: Dostop do elementov naključnega polja

 class Main ( public static void main(String() args) ( // create an array int() array = (34, 12, 44, 9, 67, 77, 98, 111); int lowerBound = 0; int upperBound = array.length; // array.length will excluded int range = upperBound - lowerBound; System.out.println("Random Array Elements:"); // access 5 random array elements for (int i = 0; i <= 5; i ++) ( // get random array index int random = (int)(Math.random() * range) + lowerBound; System.out.print(array(random) + ", "); ) ) )

Izhod

 Naključni elementi matrike: 67, 34, 77, 34, 12, 77,

Priporočene vaje

  • Math.round ()
  • Math.pow ()
  • Math.sqrt ()

Zanimive Članki...