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

时间:2017-08-17 13:15:16

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

我试图让一个随机数生成器生成一个介于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 
`.

4 个答案:

答案 0 :(得分: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 :(得分:1)

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

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

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

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

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

答案 2 :(得分:1)

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

&#13;
&#13;
extern int i;

(what can we do with i here?)
(what can't we do with i here?)
int A = i+3; // error: initializer element is not constant. This is an error not due to forward declaration of int i

int i = 3;


void fun();

(what can we do with fun here?)
(what can't we do with fun here?)

void fun(){};
&#13;
&#13;
&#13;

答案 3 :(得分:0)

Here is another way to accomplish this. Here I'm creating a variable i and storing the random number in it, then I create the while loop.

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

console.log(text);

Here is the same thing but as a do...while loop.

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