Get a random number focused on center

后端 未结 20 3003
离开以前
离开以前 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:37

    What about using something like this:

    var loops = 10;
    var tries = 10;
    var div = $("#results").html(random());
    function random() {
        var values = "";
        for(var i=0; i < loops; i++) {
            var numTries = tries;
            do {
                var num = Math.floor((Math.random() * 100) + 1);
                numTries--;
            }
            while((num < 40 || num >60) && numTries > 1)
            values += num + "
    "; } return values; }
    
    

    The way I've coded it allows you to set a couple of variables:
    loops = number of results
    tries = number of times the function will try to get a number between 40-60 before it stops running through the while loop

    Added bonus: It uses do while!!! Awesomeness at its best

提交回复
热议问题