我正在尝试制作一个随机数生成器,它可以生成1到9之间的数字字符串,如果生成了8,应该显示最后的8并停止生成。
目前它打印出1 2 3 4 5 6 7 8,但它没有生成随机数字字符串,所以我需要知道如何使循环实际上按照上述要求生成随机数。谢谢任何帮助!
JavaScript
目前它打印出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
是你的好朋友。它的意思是,生成一个从 2 到 8 的随机整数。 - ringbuffer_peek