带有if语句的do-while循环中的随机数

问题描述 投票:6回答:4

我试图让一个随机数生成器生成一个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 
`.
javascript loops random do-while do-loops
4个回答
4
投票

您可以通过更简单的方式完成此操作:

解决方案是将随机生成的数字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(' '));

1
投票

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

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

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

然后在你的循环中生成一个0到9之间的随机数.Math.floor(Math.random()*10) Concat你的字符串。如果数字是eightAppeartrue的8变化值

既然它似乎是一个练习,我会让你编码,现在应该不难:)


1
投票

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

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

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

0
投票

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

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

console.log(text);

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

i = Math.floor(Math.random() * 10)
do {
  text += i + ' ';
  i = Math.floor(Math.random() * 10)
} while (i !== 8)
  text += i;
console.log(text);
© www.soinside.com 2019 - 2024. All rights reserved.