【问题标题】:Random Number in a do-while loop with if statement带有 if 语句的 do-while 循环中的随机数
【发布时间】:2018-01-25 22:18:21
【问题描述】:

我正在尝试制作一个随机数生成器,它生成一串介于 1 和 9 之间的数字,如果它生成一个 8,它应该最后显示 8,然后停止生成。

到目前为止,它会打印 1 2 3 4 5 6 7 8,但它不会生成随机数字串,所以我需要知道如何使循环实际生成如上所述的随机数,感谢您的帮助!

Javascript

// 5. BONUS CHALLENGE: Write a while loop that builds a string of random 
integers
// between 0 and 9. Stop building the string when the number 8 comes up.
// Be sure that 8 does print as the last character. The resulting string 
// will be a random length.
print('5th Loop:');
text = '';

// Write 5th loop here:
function getRandomNumber( upper ) {
  var num = Math.floor(Math.random() * upper) + 1;
  return num;

}
i = 0;
do {
  i += 1;

    if (i >= 9) {
      break;
    }
  text += i + ' ';
} while (i <= 9);


print(text); // Should print something like `4 7 2 9 8 `, or `9 0 8 ` or `8 
`.

【问题讨论】:

  • Math.ceil(Math.random() * 7) + 1 是你的朋友。
  • 你的逻辑看起来有缺陷。

标签: javascript loops random do-while do-loops


【解决方案1】:

这是实现此目的的另一种方法。在这里,我创建了一个变量 i 并将随机数存储在其中,然后创建了 while 循环。

i = Math.floor(Math.random() * 10)
while (i !== 8) {
  text += i + ' ';
  i = Math.floor(Math.random() * 10)
}
  text += i;

console.log(text);

这里是同样的事情,但作为一个 do...while 循环。

i = Math.floor(Math.random() * 10)
do {
  text += i + ' ';
  i = Math.floor(Math.random() * 10)
} while (i !== 8)
  text += i;
console.log(text);

【讨论】:

    【解决方案2】:

    你可以用更简单的方式来做:

    解决方案是将push随机生成的数字放入一个数组中,然后使用join方法将数组的所有元素加入所需的字符串。

    function getRandomNumber( upper ) {
      var num = Math.floor(Math.random() * upper) + 1;
      return num;
    }
    var array = [];
    do { 
      random = getRandomNumber(9);
      array.push(random);
    } while(random != 8)
    console.log(array.join(' '));

    【讨论】:

      【解决方案3】:

      不是因为它更好,而是因为我们可以(而且我喜欢生成器 :)),一个带有迭代器函数的替代方案(需要 ES6):

      function* getRandomNumbers() {
        for(let num;num !==8;){
          num = Math.floor((Math.random() * 9) + 1);   
          yield num;    
        }
      }
      
      let text= [...getRandomNumbers()].join(' ');
      console.log(text); 

      【讨论】:

        【解决方案4】:

        print() 是一个打印文档的函数,你应该使用 console.log() 在控制台中显示。

        在循环之前放置一个布尔值,例如 var eightAppear = false

        你的情况现在看起来像do {... }while(!eightAppear)

        然后在循环中生成一个介于 0 和 9 之间的随机数。Math.floor(Math.random()*10) 连接你的字符串。如果数字为 8,则将 eightAppear 的值更改为 true

        既然是练习题,那我就让你写代码吧,现在应该不难了:)

        【讨论】:

          猜你喜欢
          • 2021-03-08
          • 1970-01-01
          • 2020-12-15
          • 2023-02-06
          • 2015-08-03
          • 2022-11-28
          • 2023-02-15
          • 2012-12-02
          • 1970-01-01
          相关资源
          最近更新 更多