Maison  >  Questions et réponses  >  le corps du texte

javascript - Comment obtenir un nombre aléatoire dans une plage symétrique en JS?

Par exemple, je souhaite utiliser Math.random() pour obtenir des nombres aléatoires dans les deux plages de -20~-10 et 10~20. Existe-t-il la solution la plus simple ? Par exemple, cela peut-il être fait sans instruction if ? Merci à tous d'avoir dissipé la confusion.

淡淡烟草味淡淡烟草味2662 Il y a quelques jours769

répondre à tous(4)je répondrai

  • phpcn_u1582

    phpcn_u15822017-07-05 10:46:41

    (Math.floor(Math.random() * (20 - 10 + 1)) + 10) * (Math.random() < 0.5 ? -1 : 1)

    répondre
    0
  • 某草草

    某草草2017-07-05 10:46:41

    function getRandom(min,max){
        return Math.random()*(max-min)+min;
    }

    répondre
    0
  • 为情所困

    为情所困2017-07-05 10:46:41

    Math.random() * (max - min) + min;

    Voir les détails


    Modification :

    (Math.random() * (max - min) + min)*(Math.random()<0.5?1:-1);
    

    répondre
    0
  • 欧阳克

    欧阳克2017-07-05 10:46:41

    function rand(min, max) {
        if ( min >= max ) {
            return;
        }
        return  Math.floor(min + (max - min+1) * Math.random());
    }

    Il s'agit de prendre un entier dans une plage

    répondre
    0
  • Annulerrépondre