• 红包金额随机数的生成


     <form>
    红包个数:<input type="text" name="count" id="count" required style="height: 20px;"> <br>
    总金额(元):<input type="text" name="amount" id="amount" required style="height: 20px;"><br>
    <input type="button" id="submit" value="获取红包金额">
    </form></p>
    
    <div id='result'></div>
    
    <script src="https://www.lijinma.com/javascripts/libs/jquery.min.js"></script>
    <script>
    
    $('#submit').click(function(){
      function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min)) + min;
      }
    
      function getNextItemKey(currentKey, count) {
        if (currentKey > count) {
          throw 'Error: currentKey > count';
        }
        if (currentKey != count) {
          return currentKey + 1;
        } else {
          return 1;
        }
      }
      
      var count = $('#count').val();
      var amount = $('#amount').val();
      if (!count) {
        alert('红包个数必须填写');
        return false;
      }
      if (!amount) {
        alert('总金额必须填写');
        return false;
      }
      if (amount / count < 0.01) {
        alert('单个红包金额不可低于0.01元,请重新填写金额');
        return false;
      }
      amount = amount * 100;
      var items = [];
      for (var i = 0; i < count; ++ i) {
        items[i] = getRandomInt(1, 100);
      }
      var itemAmounts = [];
      var sum = items.reduce(function(pv, cv) { return pv + cv; }, 0);
      var currentAmount = 0;
      for (var i = 0; i < count; ++ i) {
        if (i !== count - 1) {
          itemAmounts[i] = Math.floor(items[i] / sum * amount);
          currentAmount += itemAmounts[i];
        } else {
          itemAmounts[i] = amount - currentAmount
        }
      }
      
      for (var i = 0; i < count; ++ i ) {
        if (itemAmounts[i] > 0) {
          continue;
        }
        var nextKey = getNextItemKey(i, count);
        var diff = 1 - itemAmounts[i];
        itemAmounts[i] = 1;
        itemAmounts[nextKey] -= diff;
      }
      
      for (var i = 0; i < count; ++ i ) {
        itemAmounts[i] = itemAmounts[i] / 100;
      }
      
      alert(itemAmounts.join('')+'');
      
    });
    </script>
  • 相关阅读:
    冲刺 09
    冲刺08
    个人作业-买书
    冲刺07
    冲刺 06
    软件工程 寻找小水王
    冲刺04
    冲刺 03
    冲刺 02
    冲刺3
  • 原文地址:https://www.cnblogs.com/dwb91/p/7156777.html
Copyright © 2020-2023  润新知