[英]How do I get my program to print 100 random numbers and sort them from 1 to 100 in a correct way
I got the sort and printout part of the program working, but i need to generate 100 random numbers between 1 and 100 and sort them.我得到了程序的排序和打印输出部分,但我需要生成 1 到 100 之间的 100 个随机数并对它们进行排序。 But I am not sure what is missing from the program to make it work correctly.
但我不确定程序中缺少什么才能使其正常工作。 I created an array to store the numbers in it and I made sure to specify the number of numbers I wanted and that it should be from 1-100.
我创建了一个数组来存储其中的数字,并确保指定我想要的数字数量,并且它应该是从 1 到 100。
<script>
var arr = [];
while(arr.length < 100){
var r = Math.floor(Math.random() * 100) + 1;
numbers.sort();
numbers.sort(function(a, b){
return a - b;
});
document.write(numbers);
</script>
You had error in your while loop你的 while 循环出错了
var cnt = 0;
while (cnt < 100) {
var r = Math.floor(Math.random() * 100) + 1;
arr[cnt] = r;
cnt++;
}
arr.sort(function(a, b) {
return a - b;
});
document.write(arr);
Try尝试
[...Array(100)].map(x=> 1+Math.random()*100|0).sort((a,b)=>a-b);
a= [...Array(100)].map(x=> 1+Math.random()*100|0).sort((a,b)=>ab); console.log(a);
You can achieve this in a few lines using Array.from()
method and { length: n }
option like:您可以使用
Array.from()
方法和{ length: n }
选项在几行中实现这一点,例如:
const numbers = Array.from({length:100},()=>Math.floor(100*Math.random())+1); numbers.sort((a, b)=> a - b); console.log( numbers )
.as-console-wrapper { max-height: 100% !important; top: 0; }
Just modified your code, to add numbers into the array.刚刚修改了您的代码,将数字添加到数组中。
var numbers = [];
var i = 0;
while (i < 100) {
var r = Math.floor(Math.random() * 100) + 1;
numbers[i] = r;
i++;
}
//numbers.sort();
numbers.sort(function(a, b) {
return a - b;
});
document.write(numbers);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.