【问题标题】:Javascript: How to get first random number always to be higher than the second random numberJavascript:如何让第一个随机数始终高于第二个随机数
【发布时间】:2012-04-12 23:05:17
【问题描述】:
        $(function() {  
            var number = document.getElementById("breuken");        

            var i=0;

                for (i=1;i<=10;i++){
                    var fRandom = Math.floor(Math.random()*10);
                    var sRandom = Math.floor(Math.random()*10);

                    var calc = fRandom - sRandom;

                    number.innerHTML += "" + fRandom + " - " + sRandom + " = " + calc + "<br />";
                }       

            number.innerHTML;
        });

基本上,它现在的作用是显示 2 个小于 10 的随机数。它从第一个数字中减去第二个数字。

我希望第一个数字始终高于第二个数字,这样我就不会得到任何答案,例如“-3”。

【问题讨论】:

    标签: javascript function random numbers


    【解决方案1】:

    您可以在 [0;fRandom] 范围内生成第二个数字:

    var fRandom = Math.floor(Math.random()*10);
    var sRandom = Math.floor(Math.random()*fRandom);
    

    或者只是交换值:

    var fRandom = Math.floor(Math.random()*10);
    var sRandom = Math.floor(Math.random()*10);
    if(sRandom<fRandom) {
        var temp = sRandom;
        sRandom = fRandom;
        fRandom = temp;
    }
    

    【讨论】:

      【解决方案2】:

      只需使用Math.abs() 吗?

      var calc = Math.abs(fRandom - sRandom);
      

      如果订单很重要,你也可以这样做

                      var sRandom = Math.floor(Math.random()*10);
      
                      // lower bound of sRandom, upper bound of (10 - sRandom)
                      var fRandom = Math.floor(sRandom + Math.random()*(10-sRandom)); 
      

      【讨论】:

      • 在这种情况下,OP 必须更改顺序以使显示的表达式正确
      【解决方案3】:

      在减去之前添加更多行:

      if(fRandom < sRandom)
           fRandom = (sRandom - fRandom ) + Math.floor((Math.random() *10));
      

      【讨论】:

        【解决方案4】:

        如果您需要这样的随机数,请使用

        var fRandom = Math.floor(Math.random()*10);
        var sRandom = Math.floor(Math.random()*fRandom);
        

        【讨论】:

          【解决方案5】:

          要么

          var fRandom = Math.floor(5 + Math.random()*5);
          var sRandom = Math.floor(Math.random()*5);
          

          或者只是在结果上调用Math.abs()

          【讨论】:

            【解决方案6】:

            最简单的解决方案是取绝对值:

            var calc = Math.abs(fRandom - sRandom);
            

            但由于您还列出了第一个和第二个数字,您可能希望使用最小值和最大值对值进行排序并重新存储它们:

            var bigRandom = Math.max(fRandom, sRandom);
            var lilRandom = Math.min(fRandom, sRandom);
            
            var calc = bigRandom - lilRandom;
            
            number.innerHTML += "" + bigRandom + " - " + lilRandom + " = " + calc + "<br />";
            

            【讨论】:

              猜你喜欢
              • 2022-11-21
              • 1970-01-01
              • 2013-01-06
              • 2020-12-30
              • 2012-04-29
              • 2021-12-21
              • 2018-04-06
              • 2015-08-06
              • 2012-01-25
              相关资源
              最近更新 更多