An warware: bazuwar int tsakanin lambobi biyu javascript

Babban matsala tare da bazuwar int tsakanin lambobi biyu shine cewa yana iya haifar da sakamako mara tabbas. Wannan saboda ba koyaushe ana rarraba lambobi daidai-da-wane ba, kuma wannan na iya shafar sakamakon bazuwar int.

Math.floor(Math.random() * (max - min + 1)) + min

Wannan layin lambar yana haifar da lamba bazuwar tsakanin ฦ™imar min da max.

Math.bene yana zagaya lambar zuwa lamba mafi kusa.
Math.random yana haifar da ฦ™ima tsakanin 0 da 1.
ฦ˜addamar da hakan ta (max - min + 1) yana ba ku kewayo tsakanin 0 da (max - min + 1), wanda aka ฦ™ara zuwa min, yana ba ku iyakar ฦ™arshe tsakanin min da max.

bazuwar lambobi

Akwai ฦดan hanyoyi don bazuwar lambobi a JavaScript. Hanya ษ—aya ita ce amfani da aikin Math.random(). Wannan aikin yana dawo da lambar bazuwar tsakanin 0 da 1 .

Wata hanya don bazuwar lambobi ita ce amfani da aikin Math.floor(). Wannan aikin yana zagaye lamba zuwa ฦ™imar lamba mafi kusa. Don haka, idan kuna son zaษ“i tsakanin 2 da 3 ba da gangan ba, zaku yi amfani da Math.floor(2) azaman lambar bazuwar ku, da Math.floor(3) azaman lambar bazuwar ku idan 3 shine ฦ™imar da aka zaษ“a.

Shafi posts:

Leave a Comment