Get a random number focused on center

后端 未结 20 3038
离开以前
离开以前 2020-12-12 09:28

Is it possible to get a random number between 1-100 and keep the results mainly within the 40-60 range? I mean, it will go out of that range rarely, but I want it to be main

20条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-12 09:45

    I might do something like setup a "chance" for the number to be allowed to go "out of bounds". In this example, a 20% chance the number will be 1-100, otherwise, 40-60:

    $(function () {
        $('button').click(function () {
            var outOfBoundsChance = .2;
            var num = 0;
            if (Math.random() <= outOfBoundsChance) {
                num = getRandomInt(1, 100);
            } else {
                num = getRandomInt(40, 60);
            }
            $('#out').text(num);
        });
        
        function getRandomInt(min, max) {
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }
    });
    
    
    
    

    fiddle: http://jsfiddle.net/kbv39s9w/

提交回复
热议问题