在do-while循环中使用if语句生成随机数

6
我正在尝试制作一个随机数生成器,它可以生成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 
`.

3
Math.ceil(Math.random() * 7) + 1 是你的好朋友。它的意思是,生成一个从 2 到 8 的随机整数。 - ringbuffer_peek
你的逻辑看起来有缺陷。 - ABcDexter
4个回答

5
你可以更简单地完成它:
解决方案是将随机生成的数字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(' '));


2

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

function* getRandomNumbers() {
  for(let num;num !==8;){
    num = Math.floor((Math.random() * 9) + 1);   
    yield num;    
  }
}

let text= [...getRandomNumbers()].join(' ');
console.log(text); 


1

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

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

现在你的条件看起来像这样:do {…} while (!eightAppear)

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

由于这似乎是一项练习,我会让你编写它,现在应该不难了 :)


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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接