【发布时间】: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