|
6.4.. Napisati program koji generiše četverocifren broj, ispiše ga. Zatmi ispiše cifre u obrnutom redoslijedu jednu ispod druge. Opis programa: Slučajan broj se generiše funkcijom random() iz biblioteke Math u opsegu [0 , 1): nula je uključena a jedan nije uključen u opseg. Četverocifren broj se računa na osnovu izraza: = (max-min) * rnd + min odnosno: (10000 - 1000) * Math.random() + 1000. Za cjelobrojne vrijednosti se koristi (int) (Vidi Slučajan broj /RANDOM/ - funkcija Math.random()) Listing programa:
// 06421118
public class Main {
public static void main(String[] args) {
System.out.println("Cifre slucajanog cetverocifrenog broja"); // naslov
int broj = (int) ((10000 - 1000) * Math.random() + 1000); // slucajan cetverocifren broj
System.out.println("Slucajan cetverocifren broj = " + broj); // ispis
int h, s, d, j; // deklarisanje varijabli
h = broj / 1000; // cifra hiljadica
s = (broj / 100) % 10; // cifra stotica
d = (broj / 10) % 10; // cifra desetica
j = broj % 10; // cifra jedinica
System.out.println("cifra jedinica = " + j );
System.out.println("cifra desetica = " + d );
System.out.println("cifra stotica = " + s );
System.out.println("cifra hiljadica = " + h );
}
}
II varijanta izdvajanje cifara s desna
// 06421118
public class Main {
public static void main(String[] args) {
System.out.println("Cifre slucajanog cetverocifrenog broja"); // naslov
int max = 10000; // maksimalna vrijednost + 1 (cetverocifreni 9999+1=10000)
int min = 1000; // minimalna vrijednos (cetverocifreni 1000)
int broj = (int) ((max - min) * Math.random() + min); // slucajan cetverocifren broj
System.out.println("Slucajan cetverocifren broj = " + broj); // ispis
int h, s, d, j, t, obr;// deklarisanje varijabli
j = broj % 10; // cifra jedinica
t = broj / 10; // prve tri cifre
d = t % 10; // cifra desetica
t = t / 10; // prve dvije cifre
s = t % 10; // cifra stotica
h = t / 10; // cifra hiljadica
System.out.println("cifra jedinica = " + j );
System.out.println("cifra desetica = " + d );
System.out.println("cifra stotica = " + s );
System.out.println("cifra hiljadica = " + h );
}
}
III varijanta izdvajanje cifara s desna
// 06421118
public class Main {
public static void main(String[] args) {
System.out.println("Cifre slucajanog cetverocifrenog broja"); // naslov
int broj = (int) ((10000 - 1000) * Math.random() + 1000); // slucajan cetverocifren broj
System.out.println("Slucajan cetverocifren broj = " + broj); // ispis
int h, s, d, j, t, obr;// deklarisanje varijabli
j = broj % 10; // cifra jedinica
t = broj / 10; // prve tri cifre
d = t % 10; // cifra desetica
t = t / 10; // prve dvije cifre
s = t % 10; // cifra stotica
h = t / 10; // cifra hiljadica
System.out.println("cifra jedinica = " + j );
System.out.println("cifra desetica = " + d );
System.out.println("cifra stotica = " + s );
System.out.println("cifra hiljadica = " + h );
}
}
Ispis na ekranu:
Slucajan trocifren broj je : 1387
7
8
3
1
|
||||||||
|