An warware: math.random tsakanin 1 zuwa 10

ฦ˜ididdigar ฦ™ididdige lambobi na iya zama babban ษ“angaren aikace-aikace da yawa, musamman a cikin ci gaban wasa, ฦ™irar ฦ™ididdiga, da kwaikwaya. Harshen shirye-shiryen Java yana ba da aikin ginannen aiki don samar da irin waษ—annan lambobin bazuwar. Aiki ษ—aya shine Math.random(), kodayake yana haifar da ฦ™ima biyu tsakanin 0.0 (haษ—e) da 1.0 (keษ“e). Don samar da adadin bazuwar tsakanin kewayon kewayon kamar 1 zuwa 10, ana buฦ™atar ฦ™arin matakai. Wannan labarin yana zurfafa cikin ฦ™irฦ™irar lambobi tsakanin 1 da 10 a Java ta amfani da Math.random().

ฦ˜irฦ™irar Lambobin Random tare da Math.random()

Aikin Java's Math.random() yana dawo da ingantaccen ฦ™ima biyu wanda ya fi ko daidai da 0.0 kuma ฦ™asa da 1.0. Wadannan dabi'un ana samar da su ne ba da gangan ba, ma'ana cewa tsararrakinsu suna bin takamaiman algorithm amma suna bayyana bazuwar ga mai amfani.

double randomValue = Math.random();

Koyaya, don samar da lamba tsakanin 1 da 10, ba za mu iya yin amfani da Math.random() kai tsaye ba. Madadin haka, muna buฦ™atar sarrafa ฦ™imar ninki biyu da Math.random() ya dawo.

Hanyar Samar da Integers Bazuwar Tsakanin 1 da 10

Don yin kwatankwacin ฦ™irฦ™irar lambar bazuwar tsakanin 1 da 10, za mu ninka sakamakon Math.random() da 10, ฦ™ara 1, sannan mu jefa sakamakon zuwa lamba (saboda Math.random() ya dawo sau biyu) . Yin jifa zuwa lamba yana yanke juzu'i na decimal, ta haka yana ba mu ฦ™imar lamba.

int randomInteger = (int)(Math.random() * 10 + 1);

Wannan lambar tana aiki ne saboda Math.random() yana ba da ฦ™ima daga 0.0 zuwa ฦ™asa da 1.0. Lokacin da kuka ninka wannan ta 10, yana shimfiษ—a kewayon zuwa 0.0 zuwa ฦ™asa da 10.0. ฦ˜ara 1 yana canza wannan kewayon har ya zama daga 1.0 zuwa kawai ฦ™asa da 11.0.

Rushewar mataki-mataki

Bari mu zurfafa zurfafa cikin yadda lambar ke aiki:

1.

  • Ana kiran aikin Math.random(), wanda ke dawo da pseudorandom ninki biyu fiye da ko daidai da 0.0 da ฦ™asa da 1.0.
  • Ana ninka wannan ฦ™imar sau biyu ta 10. Yanzu ฦ™imar ninki biyu ta faษ—i tsakanin 0.0 da 10.0, har yanzu ฦ™asa da 10.0.
  • Mun ฦ™ara 1 zuwa sakamakon. ฦ˜imar ninki biyu yanzu tsakanin 1.0 da 11.0, har yanzu ฦ™asa da 11.0.
  • A ฦ™arshe, muna yin nau'in simintin gyare-gyare don canza sau biyu zuwa lamba. Wannan yana yanke sashin goma kuma muna samun lamba tsakanin 1 da 10.

Dakunan karatu da Ayyuka masu alaฦ™a da ฦ˜irฦ™irar Lamba bazuwar

Baya ga Math.random(), Java yana ba da wasu hanyoyi don samar da lambobi bazuwar kamar su Random class da ThreadLocalRandom class. Ajin Random yana ba da hanyoyi don samar da lambobi masu ฦ™ima iri daban-daban, kamar int, biyu, dogaye, iyo, Boolean, da sauransu. Ajin Zauren Random yana ba da hanyoyin samar da lambobi masu ฦ™ima a ฦ™arฦ™ashin yanayi na lokaci guda.

Ayyukan da aka gina a cikin Java da azuzuwan suna ba da cikakkiyar mafita don ฦ™irฦ™irar lambobi bazuwar, biyan buฦ™atu da aikace-aikace iri-iri.

Shafi posts:

Leave a Comment